概述
SQLiteDatabase是Android提供的用来管理Sqlite database的一种数据持久化解决方案。SQLiteDatabase提供了基本的增删改查方法,可以执行SQL命令,执行其他常见数据库管理任务的方法。
基本用法
如果对SQL的基本语法有一定了解,SQLiteDatabase的使用将非常简单。步骤如下:
- 1、派生抽象类SQLiteOpenHelper定义自己的DBHelper,重写onCreate和onUpgrade两个抽象方法。其中,在onCreate方法中创建数据库表,在onUpgrade方法中处理database升级问题。
public class DBHelper extends SQLiteOpenHelper {
private static final String TAG = "DBHelper";
private static final String DATABASE_NAME = "Database.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "student";
public static final String COLUMN_ID = "id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_GENDER = "gender";
public static final String COLUMN_NUMBER = "number";
public static final String COLUMN_SCORE = "score";
public static final String[] TABLE_COLUMNS = {
COLUMN_ID,
COLUMN_NAME,
COLUMN_GENDER,
COLUMN_NUMBER,
COLUMN_SCORE
};
public DBHelper(Context context) {
this(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION);
}
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version, DatabaseErrorHandler errorHandler) {
super(context, DATABASE_NAME, factory, DATABASE_VERSION, errorHandler);
}
@Override
public void onCreate(SQLiteDatabase database) {
String sql = "CREATE TABLE IF NOT EXISTS "
+ TABLE_NAME + " ( "
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ COLUMN_NAME + " TEXT,"
+ COLUMN_GENDER + " INTEGER, "
+ COLUMN_NUMBER + " TEXT, "
+ COLUMN_SCORE + " INTEGER)";
database.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
}
}
- 2、在Activity中实例化自定义的DBHelper就可以通过getWritableDatabase方法获得对应的SQLiteDatabase对象,通过这个对象就可以对数据库进行增删改查操作了。
private SQLiteDatabase mDatabase;
mDatabase = new DBHelper(this).getWritableDatabase();
举个例子
基于上述代码给出一个简单示例,看一下具体增删改查是如何操作的。为了方便查看数据,在增删查操作后都会去查询一次,显示表中所有数据。其中,Student是一个Gson格式的封装类,为了方便打印数据。
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
private SQLiteDatabase mDatabase;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabase = new DBHelper(this).getWritableDatabase();
}
@Override
protected void onStart() {
super.onStart();
}
@Override
protected void onResume() {
super.onResume();
insertData();
queryData();
updateData();
queryData();
deleteData();
queryData();
}
@Override
protected void onPause() {
super.onPause();
}
@Override
protected void onStop() {
super.onStop();
}
@Override
protected void onDestroy() {
super.onDestroy();
}
private void insertData() {
Log.i(TAG,"insertData");
ContentValues contentValues = new ContentValues();
contentValues.put("id",0);
contentValues.put("name","peter");
contentValues.put("gender",0);
contentValues.put("number","201804081705");
contentValues.put("score","100");
mDatabase.insertWithOnConflict(DBHelper.TABLE_NAME,null,contentValues,SQLiteDatabase.CONFLICT_IGNORE);
contentValues = new ContentValues();
contentValues.put("id",1);
contentValues.put("name","lemon");
contentValues.put("gender",1);
contentValues.put("number","201804111048");
contentValues.put("score","90");
mDatabase.insertWithOnConflict(DBHelper.TABLE_NAME,null,contentValues,SQLiteDatabase.CONFLICT_IGNORE);
}
private void deleteData() {
Log.i(TAG,"deleteData");
mDatabase.delete(DBHelper.TABLE_NAME,"name = ?",new String[]{"update"});
}
private void updateData() {
Log.i(TAG,"updateData");
ContentValues contentValues = new ContentValues();
contentValues.put("name","update");
contentValues.put("gender",1);
contentValues.put("number","201804111048");
contentValues.put("score","100");
mDatabase.update(DBHelper.TABLE_NAME,contentValues,"name = ?",new String[]{"lemon"});
}
private void queryData() {
Cursor cursor;
cursor = mDatabase.query(DBHelper.TABLE_NAME,DBHelper.TABLE_COLUMNS,null,null,null,null,null);
try{
while (cursor != null && cursor.moveToNext()) {
Student student = new Student();
student.setId(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID)));
student.setName(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME)));
student.setGender(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_GENDER)));
student.setNumber(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NUMBER)));
student.setScore(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_SCORE)));
Log.i(TAG,"queryData student = " + student.toString());
}
} catch (SQLException e) {
Log.e(TAG,"queryData exception", e);
}
}
}
输出log如下:
com.example.peter.sqlitedatabasedemo I/MainActivity: insertData
com.example.peter.sqlitedatabasedemo I/MainActivity: queryData student = Student{id=0, name='peter', gender=0, number='201804081705', score=100}
com.example.peter.sqlitedatabasedemo I/MainActivity: queryData student = Student{id=1, name='lemon', gender=1, number='201804111048', score=90}
com.example.peter.sqlitedatabasedemo I/MainActivity: updateData
com.example.peter.sqlitedatabasedemo I/MainActivity: queryData student = Student{id=0, name='peter', gender=0, number='201804081705', score=100}
com.example.peter.sqlitedatabasedemo I/MainActivity: queryData student = Student{id=1, name='update', gender=1, number='201804111048', score=100}
com.example.peter.sqlitedatabasedemo I/MainActivity: deleteData
com.example.peter.sqlitedatabasedemo I/MainActivity: queryData student = Student{id=0, name='peter', gender=0, number='201804081705', score=100}
数据库基本操作
接下来介绍一下数据库的增删改查操作。
-
插入数据
SQLiteDatabase封装了三个方法用来插入数据,insert和insertOrThrow最终都会通过insertWithOnConflict方法来完成数据插入。Insert方法对插入错误做了异常捕获,插入正确会返回插入的行号,插入错误会返回-1。而insertOrThrow插入错误会直接抛出SQLException异常。insertWithOnConflict相比于前两个方法多了一个conflictAlgorithm参数,可以通过这个参数指定插入发生冲突时的处理策略。
返回值类型 | 函数声明 |
---|---|
long | insert(String table, String nullColumnHack, ContentValues values) |
long | insertOrThrow(String table, String nullColumnHack, ContentValues values) |
long | insertWithOnConflict(String table, String nullColumnHack, ContentValues initialValues, int conflictAlgorithm) |
SQLiteDatabase提供的冲突处理策略及作用。
标志 | 作用 | |
---|---|---|
0 | CONFLICT_NONE | 未指定冲突解决方法 |
1 | CONFLICT_ROLLBACK | 当冲突发生,立即执行回滚操作,结束当前事务,命令终止并返回错误码SQLITE_CONSTRAINT |
2 | CONFLICT_ABORT | 当冲突发生,不执行回滚,保留同一事务内先前命令的更改。默认冲突处理策略。 |
3 | CONFLICT_FAIL | 当冲突发生,命令终止并返回错误码SQLITE_CONSTRAINT,但是错误发生前的改动被保存下来不会回退 |
4 | CONFLICT_IGNORE | 当冲突发生,发生冲突这一行将不被改变,继续执行下一条命令,并且不会返回任何错误 |
5 | CONFLICT_REPLACE | 当冲突发生,先前存在的那条数据将被替换然后继续执行下一条命令,并且不会返回任何错误 |
示例:
ContentValues contentValues = new ContentValues();
contentValues.put("id",0);
contentValues.put("name","peter");
contentValues.put("gender",0);
contentValues.put("number","201804081705");
contentValues.put("score","100");
mDatabase.insertWithOnConflict(DBHelper.TABLE_NAME,null,contentValues,SQLiteDatabase.CONFLICT_IGNORE);
-
替换数据
SQLiteDatabase提供replace和replaceOrThrow方法来替换数据,用来替换数据库中的某行数据,如果这行数据不存在则作为新数据插入到数据库。从源码来看,其本质是通过insertWithOnConflict方法加CONFLICT_REPLACE冲突处理策略来实现的。
返回值类型 | 方法名称 |
---|---|
long | replace(String table, String nullColumnHack, ContentValues initialValues) |
long | replaceOrThrow(String table, String nullColumnHack, ContentValues initialValues) |
-
删除数据
SQLiteDatabase提供delete方法用来删除数据,返回值为被删除数据的行数。
示例:
mDatabase.delete(DBHelper.TABLE_NAME,"name = ?",new String[]{"update"});
其中,“?”是占位符,执行时会被替换为第三个参数中的"update"。
-
更新数据
SQLiteDatabase封装了update和updateWithOnConflict两个方法用来更新数据。update也是调用updateWithOnConflict来完成更新操作。与插入数据方法insertWithOnConflict类似,updateWithOnConflict相比于update方法多了一个conflictAlgorithm参数,用法可以参看前面对这些策略的介绍。
返回值类型 | 函数声明 |
---|---|
int | update(String table, ContentValues values, String whereClause, String[] whereArgs) |
int | updateWithOnConflict(String table, ContentValues values, String whereClause, String[] whereArgs, int conflictAlgorithm) |
示例:
ContentValues contentValues = new ContentValues();
contentValues.put("name","update");
contentValues.put("gender",1);
contentValues.put("number","201804111048");
contentValues.put("score","100");
mDatabase.update(DBHelper.TABLE_NAME,contentValues,"name = ?",new String[]{"lemon"});
-
查询数据
Android中的数据查询跟SQLite一样,是所有操作中最复杂的一个,因此,在SQLiteDatabase中为查询数据封装了非常多的方法供用户根据自己的需要选择使用。通过源码可以看出,query开头的查询方法最后都会通过queryWithFactory方法来查询,而queryWithFactory最终会调用rawQueryWithFactory来执行查询。
返回值类型 | 函数声明 |
---|---|
Cursor | query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) |
Cursor | query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) |
Cursor | query(boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal) |
Cursor | query(String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy) |
Cursor | queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit, CancellationSignal cancellationSignal) |
Cursor | queryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, boolean distinct, String table, String[] columns, String selection, String[] selectionArgs, String groupBy, String having, String orderBy, String limit) |
Cursor | rawQuery(String sql, String[] selectionArgs, CancellationSignal cancellationSignal) |
Cursor | rawQuery(String sql, String[] selectionArgs) |
Cursor | rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable, CancellationSignal cancellationSignal) |
Cursor | rawQueryWithFactory(SQLiteDatabase.CursorFactory cursorFactory, String sql, String[] selectionArgs, String editTable) |
示例:
Cursor cursor;
cursor = mDatabase.query(DBHelper.TABLE_NAME,DBHelper.TABLE_COLUMNS,null,null,null,null,null);
try{
while (cursor != null && cursor.moveToNext()) {
Student student = new Student();
student.setId(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_ID)));
student.setName(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NAME)));
student.setGender(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_GENDER)));
student.setNumber(cursor.getString(cursor.getColumnIndex(DBHelper.COLUMN_NUMBER)));
student.setScore(cursor.getInt(cursor.getColumnIndex(DBHelper.COLUMN_SCORE)));
Log.i(TAG,"queryData student = " + student.toString());
}
} catch (SQLException e) {
Log.e(TAG,"queryData exception", e);
}
以“raw”为前缀和没有前缀的方法有什么区别呢?比如:你在使用的时候有没有注意过query和rawQuery有什么区别?从源码中的注释可以得到答案,不带“raw”前缀的方法比如query是Android中提供的封装后的方法,而以“raw”为前缀的方法是SQL提供的方法。
/**
* Runs the provided SQL and returns a {@link Cursor} over the result set.
*
* @param sql the SQL query. The SQL string must not be ; terminated
* @param selectionArgs You may include ?s in where clause in the query,
* which will be replaced by the values from selectionArgs. The
* values will be bound as Strings.
* @return A {@link Cursor} object, which is positioned before the first entry. Note that
* {@link Cursor}s are not synchronized, see the documentation for more details.
*/
public Cursor rawQuery(String sql, String[] selectionArgs) {
return rawQueryWithFactory(null, sql, selectionArgs, null, null);
}
SQLiteDatabase中的其他方法
-
execSQL
上面介绍的增删改查等数据库基本操作只能完成一些比较简单的数据库操作,对于一些复杂的数据操作,比如多种操作结合的语句就无能为力了。所以,SQLiteDatabase提供了execSQL方法来直接执行SQL语句。
返回值类型 | 函数声明 |
---|---|
void | execSQL(String sql) |
void | execSQL(String sql, Object[] bindArgs) |
-
getVersion
获得当前database的版本,不同版本的数据结构可能不同,通过getVersion方法获得当前的database的版本号,可以根据不同版本实现对应的逻辑。
-
打开数据库
SQLiteDatabase中定义了很多打开数据库的方法,可以通过这些方法直接打开给定目录下的database,并对数据进行操作。
返回值类型 | 方法名 |
---|---|
static SQLiteDatabase | openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags) |
static SQLiteDatabase | openDatabase(File path, SQLiteDatabase.OpenParams openParams) |
static SQLiteDatabase | openDatabase(String path, SQLiteDatabase.CursorFactory factory, int flags, DatabaseErrorHandler errorHandler) |
static SQLiteDatabase | openOrCreateDatabase(File file, SQLiteDatabase.CursorFactory factory) |
static SQLiteDatabase | openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) |
static SQLiteDatabase | openOrCreateDatabase(String path, SQLiteDatabase.CursorFactory factory) |
Android中的数据库事务
使用事务的两大好处是原子提交和提升性能。原子提交意味着同一事务内的所有修改要么都完成要么都不做,如果某个修改失败,会自动回滚使得所有修改不生效。SQLite默认会为每个插入、更新操作创建一个事务,并且在每次插入、更新后立刻提交。如果连续插入n次数据,就会重复执行n次创建事务->执行语句->提交操作。如果主动创建事务,那么这个过成就被优化为创建事务->执行n条语句->提交操作,创建事务和提交操作只执行了一次,可以使性能大幅提高。Android中使用数据库事务代码如下:
//事务开始
database.beginTransaction();
try {
//执行操作语句
...
//事务成功
database.setTransactionSuccessful();
} catch (Exception e) {
e.printStackTrace();
} finally {
//事务结束
database.endTransaction();
}
数据库升级
随着系统的升级,我们的业务可能发生变化,导致数据结构发生了改变,产生的问题是数据库也要随着升级。Android中的数据库根据数据版本号来判断数据库是否进行升级。数据库升级需要重写onUpgrade方法,修改相关逻辑,最后还需要把database的版本号加一。简单示例代码如下:
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
Log.i(TAG,"onUpgrade oldVersion = " + oldVersion + " , newVersion =" + newVersion);
switch (oldVersion) {
case 1:
upgradeFromVersion1(database);
break;
default:
Log.i(TAG,"Do not have this case !");
}
}
private void upgradeFromVersion1(SQLiteDatabase database) {
Log.i(TAG,"upgradeFromVersion1");
//do something
}
升级运行log如下:
com.example.peter.sqlitedatabasedemo I/DBHelper: onUpgrade oldVersion = 1 , newVersion =2
com.example.peter.sqlitedatabasedemo I/DBHelper: upgradeFromVersion1
数据库降级
数据库能够升级,自然也能够降级,只需要重写onDowngrade方法并修改相应逻辑,最后把database的版本号减一即可。注意在重写onDowngrade的时候不要调用父类onDowngrade方法,否则会抛出SQLiteException异常。异常信息如下:
Caused by: android.database.sqlite.SQLiteException: Can't downgrade database from version 2 to 1
这是为什么呢?我们来看一下SQLiteOpenHelper类的源码。
/**
* Called when the database needs to be downgraded. This is strictly similar to
* {@link #onUpgrade} method, but is called whenever current version is newer than requested one.
* However, this method is not abstract, so it is not mandatory for a customer to
* implement it. If not overridden, default implementation will reject downgrade and
* throws SQLiteException
*
* <p>
* This method executes within a transaction. If an exception is thrown, all changes
* will automatically be rolled back.
* </p>
*
* @param db The database.
* @param oldVersion The old database version.
* @param newVersion The new database version.
*/
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
throw new SQLiteException("Can't downgrade database from version " +
oldVersion + " to " + newVersion);
}
从实现逻辑和代码注释中得到了明确的答案——默认情况下会拒绝数据库的降级操作并抛出SQLiteException异常。所以解决方案就是不调用父类的onDowngrade方法,最终的代码如下:
@Override
public void onDowngrade(SQLiteDatabase database, int oldVersion, int newVersion) {
//重写onDowngrade的时候不要调用父类onDowngrade方法
//super.onDowngrade(database, oldVersion, newVersion);
Log.i(TAG,"onDowngrade oldVersion = " + oldVersion + " , newVersion =" + newVersion);
switch (oldVersion) {
case 2:
downgradeFromVersion2(database);
break;
default:
Log.i(TAG,"Do not have this case !");
}
}
private void downgradeFromVersion2(SQLiteDatabase database) {
Log.i(TAG,"downgradeFromVersion2");
//do something
}
降级运行log如下
com.example.peter.sqlitedatabasedemo I/DBHelper: onDowngrade oldVersion = 2 , newVersion =1
com.example.peter.sqlitedatabasedemo I/DBHelper: downgradeFromVersion2
其他
我们看到如果使用原生的SQL语句来保存数据库,代码量减少了很多。但是android为什么推荐我们使用它封装的方法呢?首先,SQL语句不能出现拼写错误或是语法错误,否则会导致应用崩溃。其次,使用封装方法只需要根据参数要求传递相应参数,方法内部会自动把这些参数按照SQL语法规则组合成SQL命令。最后,封装方法提供了多种冲突处理策略,使用者可以根据不同的场景需要选择合适的策略解决冲突。
SQLiteOpenHelper中有两个非常重要的实例方法,getReadableDatabase() 和getWritableDatabase()。这两个方法都可以创建或打开一个现有的数据库(如果数据库已存在则直接打开,否则创建一个新的数据库),并返回一个可对数据库进行读写操作的对象。不同的是,当数据库不可写入的时候(如磁盘空间已满)getReadableDatabase()方法返回的对象将以只读的方式去打开数据库,而getWritableDatabase()方法则将出现异常。
总结
本文在开篇简单介绍了通过SQLiteDatabase进行数据存储的基本用法,然后参照SQLiteDatabase源码对其提供的主要方法进行分类和整理,并分析了同种操作不同方法之间的差异,最后介绍了如何升级和降级数据库,以及从源码角度分析了降级过程中遇到的坑。