Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Android数据存储方式―SQLite SQLite Android 数据存储方式

$
0
0
Android数据存储方式—SQLite
SQLite
Android平台嵌入了一个关系型数据库SQLite,和其他数据库不同的是:SQLite存储数据时,不需要指定数据类型
一个字段声明为Integer类型,我们可以将一个字符串存入;一个字段声明为Boolean,我们也可以存入浮点数。
除非是主键被定义为integer,这时只能存储64位整数。
SQLite只支持5种数据类型:null,integer,real,text,blob
SQLite数据库操作
SQLite不需要创建数据库
直接在adb shell中,使用sqlite3命令会自动创建一个数据库
sqlite3命令存放目录:sdk/tools/sqlite3.exe
eg:sqlite3/mnt/sdcard/test.db。在sdcard目录下创建了一个test数据库db为数据库的后缀名,可以换成其他的
创建表
创建表的时候,可以不指定数据类型
create table users(_id integer primary key autoincrement,name,age)
主键建议使用_id

SQLite支持大部分标准的SQL语句,增删改查语句都是通用的,分页查询和mysql相同

也可以使用第三方图形用户外界面操作数据库

Android使用数据库所涉及到的API

Android中不再使用JDBC方式来访问数据库,而是采用了一套新的API

创建数据库
自定义类继承SQLiteOpenHelper
/**
* Created by Administrator on 2017/2/6.
*/
public class DbHelper extends SQLiteOpenHelper {
/**
* @param context 上下文Context
* @param name 数据库名字(文件名)
* @param factory 数据库工厂(NULL)
* @param version 数据库版本
*/
public DbHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
/**
* 创建表的操作
* @param sqLiteDatabase
*/
@Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
//创建表
sqLiteDatabase.execSQL("create table person(_id integer primary key autoincrement,name,age)");
}
/**
* 数据库的版本:底----》高
* @param sqLiteDatabase
* @param i
* @param i1
*/
@Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
}
}

在MainActivity类创建该对象,调用getWritableDatabase()或者getReadableDatabase()

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化DbHelper
DbHelper dbHelper = new DbHelper(this, "persons.db", null, 1);
//获取SqlLiteDataBase对象(类似Hibernate中Session)
db = dbHelper.getReadableDatabase();
情况1:数据库文件不存在,创建文件,打开数据库连接,执行onCreate()方法
情况2:数据库文件存在,版本号没变,打开数据库连接
情况3:数据库文件存在,版本号升级,升级数据库,打开数据库连接,执行onUpgrade()方法
情况4:数据库文件存在,版本号降低,执行onDowngrade()方法,方法在4.0会默认抛出一个异常

getWritableDatabase()跟getReadableDatabase()区别

getReadableDatabase()在通常情况下返回的就是getWritableDatabase()拿到的数据库,只有在抛出异常时拿到的数据为只读的
在做增删改时,使用getWritableDatabase()
在做查询时,使用getReadableDatabase()
创建数据库
和JDBC访问数据库不同,操作SQLite数据库无需加载驱动,不同获取连接,直接可以使用。
获取SQLiteDatabase对象之后,通过该对象可以直接执行SQL语句
public class MainActivity extends ListActivity {
private ListView listView;
private EditText et_main_id;
private EditText et_main_name;
private EditText et_main_age;
private SQLiteDatabase db;
private Cursor cursor;
private SimpleCursorAdapter simpleCursorAdapter;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//实例化DbHelper
DbHelper dbHelper = new DbHelper(this, "persons.db", null, 1);
//获取SqlLiteDataBase对象(类似Hibernate中Session)
db = dbHelper.getReadableDatabase();
//获取ListView
listView = getListView();
initViews();
//查询所有
cursor = db.query(false, "person", null, null, null, null, null, null, null);
//循环游标
//把值放入List
//设置适配器
//SimpleCursorAdapter
simpleCursorAdapter = new SimpleCursorAdapter(this, R.layout.item_listview, cursor, new String[]{"_id", "name", "age"}, new int[]{R.id.tv_item_list_id, R.id.tv_item_list_name, R.id.tv_item_list_age});
listView.setAdapter(simpleCursorAdapter);
//初始化事件
initEvents();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
private void initEvents() {
//给listview添加长按事件
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView adapterView, View view, int i, long l) {
//获取点击的每一行值
LinearLayout root = (LinearLayout) view;
final String id = ((TextView) root.findViewById(R.id.tv_item_list_id)).getText().toString();
final String name = ((TextView) root.findViewById(R.id.tv_item_list_name)).getText().toString();
final String age = ((TextView) root.findViewById(R.id.tv_item_list_age)).getText().toString();
//弹出对话框
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final AlertDialog dialog = builder.create();
//设置点击空白,不取消对话框
dialog.setCancelable(false);
//解析布局文件
final View v = getLayoutInflater().inflate(R.layout.dialog_listview, null);
((TextView) v.findViewById(R.id.tv_dialog_listview_id)).setText("修改:" + id);
((EditText) v.findViewById(R.id.et_dialog_listview_name)).setText(name);
((EditText) v.findViewById(R.id.et_dialog_listview_age)).setText(age);
((Button) v.findViewById(R.id.btn_dialog_listview_sure)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name1 = ((EditText) v.findViewById(R.id.et_dialog_listview_name)).getText().toString();
String age1 = (((EditText) v.findViewById(R.id.et_dialog_listview_age)).getText().toString());
//实例化内容值
ContentValues contentValues=new ContentValues();
contentValues.put("name",name1);
contentValues.put("age",age1);
db.update("person",contentValues,"_id=?",new String[]{""+id});
cursor = db.rawQuery("select * from person", null);
simpleCursorAdapter.changeCursor(cursor);
Toast.makeText(MainActivity.this, "执行修改操作", Toast.LENGTH_SHORT).show();
dialog.dismiss();//关闭当前对话框
}
});
((Button) v.findViewById(R.id.btn_dialog_listview_cancel)).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
dialog.dismiss();
}
});
dialog.setView(v);
dialog.show();
return true;
}
});
}
private void initViews() {
et_main_id = (EditText) findViewById(R.id.et_main_id);
et_main_name = (EditText) findViewById(R.id.et_main_name);
et_main_age = (EditText) findViewById(R.id.et_main_age);
}
public void save(View view) {
String name = et_main_name.getText().toString();
int age = Integer.parseInt(et_main_age.getText().toString());
//保存到数据库
ContentValues values = new ContentValues();//底层为Map
values.put("name", name);
values.put("age", age);
values.putNull("_id");
db.insert("person", "name", values);
Toast.makeText(MainActivity.this, "添加成功!", Toast.LENGTH_SHORT).show();//查询所有
cursor = queryAllPerson("");
//通知适配器发生改变
simpleCursorAdapter.changeCursor(cursor);
et_main_name.setText("");
et_main_age.setText("");
}
public Cursor queryAllPerson(String name) {
// Cursor cursor = db.query(false,"person",null,null,null,null,null,null,null);
Cursor cursor;
if (!"".equals(name)) {
cursor = db.rawQuery("select * from person where name like ? limit ?,?", new String[]{"%" + name + "%", 2 + "", 2 + ""});
} else {
cursor = db.rawQuery("select * from person", null);
}
return cursor;
}
public void query(View view) {
if (TextUtils.isEmpty(et_main_name.getText())) {
//模糊查询
cursor = queryAllPerson("");
} else {
//查询所有
String name = et_main_name.getText().toString();
cursor = queryAllPerson(name);
}
//通知适配器发生改变
simpleCursorAdapter.changeCursor(cursor);
simpleCursorAdapter.notifyDataSetChanged();
}
}
上面我只做了添加查询以及长按修改功能
截取不了动图我就展示一下我做出来的效果吧!
Android数据存储方式―SQLite SQLite Android 数据存储方式
Android数据存储方式―SQLite SQLite Android 数据存储方式

Viewing all articles
Browse latest Browse all 3160

Latest Images

Trending Articles



Latest Images