关于SQLiteOpenHelper:
1.SQLite创建
public static final String CREATE_TABLE_PROVINCE =
"createtable Province ("
+ "id integer primary key autoincrement, "
+ "province_name text, "
+ "province_code text)";
onCreate(SQLiteDatabase db):
当数据库第一次被建立的时候被执行,例如创建表,初始化数据等。
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE_PROVINCE);
Log.i("CoolWeatherOpenHelper","onCreate");
}
onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):
当数据库需要被更新的时候执行,例如删除久表,创建新表。
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch newVersion:
case 1:
//todo
case 2:
//todo
case 3:
//todo
break;
}
2.SQLite的使用
Android提供了一个名为SQLiteDatabase的类,它封装了一些操作数据库的API。使用它能实现基本的CRUD操作,通过getWritableDatabase()和getReadableDatabase()可以获取数据库实例。
可以使用一个类来封装增添删改操作。
public class DB {
private static DB Db;
private SQLiteDatabase db;
//创建DB
private DB(Context context){
OpenHelper dbHelper = new OpenHelper(context, DB_NAME, null, VERSION);
db = dbHelper.getWritableDatabase();
}
//获取DB对象
public synchronized static DB getInstance(Context context){
if(Db == null){
Db = new DB(context);
}
return Db;
}
//CURD Code
}
//db可以执行的操作
// 查询
public Cursor query (String table, String[] columns, String selection, String[] selectionArgs,String groupBy, String having,String orderBy,String limit);
/**
* table 表名
* columns 想要显示的列,若为空则返回所有列,不建议设置为空,如果不是返回所有列
* selection where子句,声明要返回的行的要求,如果为空则返回表的所有行
* selectionArgs where子句对应的条件值
* groupBy 分组方式
* having having条件,若为空则返回全部(不建议)
* orderBy 排序方式,为空则为默认排序方式
* limit 限制返回的记录的条数,为空则不限制
* Cursor 返回一个Cursor对象
*/
ContentValues cv = new ContentValues();
String[] args = {String.valueOf("a")};
query("user", new String[] { "username","password" },"username=?", args, null,null, null, null);
//插入
public long insert (String table, String nullColumnHack, ContentValues values);
/**
* table 表名
* nullColumnHack 当values参数为空或者里面没有内容的时候,我们insert是会失败的(底层数据库不允许插入一个空行),为了防止这种情况,我们要在这里指定一个 列名,到时候如果发现将要插入的行为空行时,就会将你指定的这个列名的值设为null,然后再向数据库中插入
* values 一个ContentValues对象,类似一个map.通过键值对的形式存储值
* long •the row ID of the newly inserted row, or -1 if an error occurred
*/
ContentValues cv = new ContentValues();
cv.put("username", "a");
cv.put("password", "b");
insert("user", null, cv);
//更新
public int update (String table, ContentValues values, String whereClause, String[] whereArgs);
/**
* table 表名
* values 一个ContentValues对象,类似一个map.通过键值对的形式存储值
* whereClause 可选的where语句whereClause语句中表达式的?占位参数列表
* whereArgs
*/
ContentValues cv = new ContentValues();
cv.put("username", "c");
cv.put("password", "d");
String[] args = {String.valueOf("a")};
update("user", cv, "username=?",args)
//删除
public int delete (String table, String whereClause, String[] whereArgs)
/**
* table 表名
* whereClause 同上
* whereArgs
*/
ContentValues cv = new ContentValues();
String[] args = {String.valueOf("c")};
delete("user", "username=?", args);