SQLite数据库存储
一)创建数据库表
Android中使用SQLiteOpenHelper抽象类来对数据库进行创建和升级,其包含onCreate()和onUpgrade()抽象方法。
public class MyDatabasehelper extends SQLiteOpenHelper{
public static final String CREATE_BOOK="create table book("
+ "id integer primary key autoincrement,"
+"author text,"
+ "price integer,"
+ "pages integer,"
+ "name text)";
private Context mContext;
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public MyDatabasehelper(Context context, String name, CursorFactory factory, int version) {
super(context, name, factory, version);
mContext=context;
}
}
在onCreate()里面通过SQLiteDataBase的execSQL()执行建表语句。
然后在给MyDatabasehelper()实例化,它的构造方法的第二个参数代表指定的数据库名,第四个参数代表版本号。我们给MyDatabasehelpe指定为getWritableDatabase(),在点击事件里就会检测到当前程序中如果没有BookStroe.db这个数据库,就会创建该数据库并调用MyDatabasehelper的onCreate()来创建。
public class MainActivity extends Activity {
private Button Create;
private MyDatabasehelper dbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dbHelper=new MyDatabasehelper(this,"BookStore.db",null, 1);
Create=(Button) findViewById(R.id.create_data);
Create.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dbHelper.getWritableDatabase();
}
});
}
}
二)升级数据库表
还是在刚才的数据库里面,如果我们想增加一个表,就会用到onUpgrade()。
我们先新建表如下
public static final String CREATE_CATEGORY="create table Category("
+ "id integer primary key autoincrement,"
+ "category_name text,"
+ "category_code integer)";
然后在执行这条建表语句,并且在onUpgrade()执行DROP语句。
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
db.execSQL(CREATE_CATEGORY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//DROP语句,如果发现已经存在Book表或者Category表就将这两张表删除掉,再调用onCreate()重新创建
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
最后因为我们改变了数据库的表结构,需要改变MianActivity里的版本号
dbHelper=new MyDatabasehelper(this,"BookStore.db",null, 1);
三)添加数据
使用ContentValues来对数据进行组装,类似于一个装数据的容器,在这个桶或者箱子等容器里面对数据进行操作。
case R.id.add_data:
SQLiteDatabase db=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
//开始添加第一条表的数据
values.put("name","《平凡的世界》");
values.put("author","路遥");
values.put("pages", 454);
values.put("prices", 59.9);
db.insert("Book",null, values);//插入数据
values.clear();
//开始添加第二条表的数据
values.put("name","《红楼梦》");
values.put("author","曹雪芹");
values.put("pages", 508);
values.put("prices", 89.9);
db.insert("Book",null, values);//插入数据
break;
case R.id.upgrade_data:
SQLiteDatabase db=dbHelper.getWritableDatabase();
ContentValues values=new ContentValues();
values.put("price", 10.99);
db.update("Book", values, "name=?",new String[]{"《平凡的世界》"});
break;
update()的第三个参数和第四个参数表示的是SQL语句的where部分,"?"是一个占位符,通过第四个参数里提供的一个字符串数组来为每个占位符指定相对应的内容,最后结果是将名字是《平凡的世界》的这本书的价格改为10.99。
五)删除数据
第二个参数和第三个参数也是占位符和指定的内容
case R.id.delete_data:
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.delete("Book","pages>?",new String[]{"500"});//删除页数大于500的内容
使用遍历的方法来查询
case R.id.query_data:
SQLiteDatabase db=dbHelper.getWritableDatabase();
Cursor cursor=db.query("Book", null,null,null,null,null,null);
if (cursor.moveToFirst()) {
do{
String name=cursor.getString(cursor.getColumnIndex("name"));
String author=cursor.getString(cursor.getColumnIndex("author"));
int pages=cursor.getInt(cursor.getColumnIndex("pages"));
double price=cursor.getDouble(cursor.getColumnIndex("price"));
//可以对这些数据进行处理
//.......
}while(cursor.moveToNext());
}
break;
七)使用SQL语句来操作
对于习惯使用SQL而且对SQL语句比较熟悉的用户,也可以直接通过SQL语句来操作。
比如上面的例子里添加数据:
db.execSQL("insert into Book(name,author,pages,price)values(?,?,?,?)",
new String[]{"《平凡的世界》","路遥","4540","56.9"});
更新数据
db.execSQL("update Book set price=?where name=?",
new String[]{"52.9","《平凡的世界》"});//将此书的价格改为52.9
删除数据
db.execSQL("delete from Book where pages>?",
new String[]{"500"});//查询页数大于500的内容
查询数据
db.rawQuery("select * from Book", null);
用此种方法操作的结果和上面的结果完全一样。
八)事务的使用
事务可以保证操作要么全部完成,要么全部不完成。
比如我们将Book表的数据全部替换成新的数据,我们要保证删除旧数据和添加新数据的操作一起完成,否则就还要继续保留原来的旧数据。
case R.id.replace_data:
SQLiteDatabase db=dbHelper.getWritableDatabase();
db.beginTransaction();//开启事务
try {
db.delete("Book",null,null);
ContentValues values=new ContentValues();
values.put("name","《白鹿原》");
values.put("author","陈忠实");
values.put("pages", 750);
values.put("price", 20.85);
db.insert("Book", null, values);
db.setTransactionSuccessful();//事务已经执行成功
}catch (Exception e) {
e.printStackTrace();
}
finally {
db.endTransaction();//结束事务
}