getWritableDatabase(),以写的方式打开一个数据库实例
注意:当数据库不可写入的时候,前者是返回一个只能写的数据库,而后者是报异常
create table Book(
id integer primary key autoincrement,
author text,
price real,
pages integer,
name text)
public static final String CREATE_BOOK = "create table Book ("
+ "id integer primary key autoincrement,"
+ "author text,"
+ "price real,"
+ "pages integer"
+ "name text)";
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_BOOK);
Log.d("------","创建成功");
}
dbHelper = new MyDatabaseHelper(this,"BookStore.db",null,2);
SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("drop table if exists Book");
db.execSQL("drop table if exists Category");
onCreate(db);
}
SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("name","大笑江湖");
values.put("page",456);
values.put("price",20.12);
values.put("author","作者");
writableDatabase.insert("Book",null,values);
values.clear();
values.put("name","龙王传说");
values.put("page",5555555);
values.put("price",85);
values.put("author","我吃西红柿");
writableDatabase.insert("Book",null,values);
SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put("price",122);
writableDatabase.update("Book",values,"name = ?",new String[]{"龙王传说"});
SQLiteDatabase writableDatabase = dbHelper.getWritableDatabase();
writableDatabase.delete("Book","page > ?",new String[]{"200"});
SQLiteDatabase db = dbHelper.getWritableDatabase();
Cursor cursor = db.query("Book",null,null,null,null,null,null);
if(cursor.moveToFirst()){
do{
Log.d("---Query---name---",""+cursor.getString(cursor.getColumnIndex("name")));
Log.d("---Query---author---",""+cursor.getString(cursor.getColumnIndex("author")));
Log.d("---Query---price---",cursor.getDouble(cursor.getColumnIndex("price"))+"");
Log.d("---Query---pages---",""+cursor.getInt(cursor.getColumnIndex("pages")));
Log.d("-----------", "onClick: -----------------------------");
}while (cursor.moveToNext());
}else {
Log.d("----------", "onClick: 数据库为空");
}