SQLite 是一套開源的嵌入式關聯式資料庫,2000 年由 D. Richard Hipp 發布。它的好處在於大幅降低應用程式管理資料的負擔:可移植性佳、易用、體積小、效率高而且可靠。Android 內建的是 SQLite3 版本。
SQLite 不採用靜態型別,而是使用列的關聯性——也就是說型別屬於資料本身,而不是欄位屬性。當某個值寫入時,SQLite 會檢查它的型別;若與該列不匹配,會先嘗試轉換,轉不成就以原本的型別保存。支援的型別有 NULL、INTEGER、REAL、TEXT 與 BLOB。因此你可以在 Integer 欄位放字串、在布林欄位放浮點數。唯一的例外是當主鍵宣告為 INTEGER 時只能存 64 位整數,寫入其他型別會產生錯誤。另外,SQLite 解析 CREATE TABLE 時會忽略欄位名稱後面的型別資訊。
SQLite 的五個特點
SQLiteOpenHelper 抽象類別主要用來做版本管理,並非必須,但實務上很常用。它提供兩個關鍵方法:onCreate(SQLiteDatabase db) 在首次使用時建立資料表,onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 在版本升級時更新表結構。
public SQLiteOpenHelper(Context context, String name,
SQLiteDatabase.CursorFactory factory, int version)
public class DatabaseHelper extends SQLiteOpenHelper {
static String dbName = "myAndroid_db.db";
static int version = 1;
public DatabaseHelper(Context context) {
super(context, dbName, null, version);
}
// 第一次使用的時候會被調用,用來建庫
public void onCreate(SQLiteDatabase db) {
String sql = "create table person11(personid integer primary key
autoincrement, name varchar(20), age integer)";
db.execSQL(sql);
}
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion) {
String sql = "drop table if exists person";
onCreate(db);
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String sql = "alter table person add phone char(20) null";
db.execSQL(sql);
}
實務上更安全的做法是用 alter table 新增欄位,而不是直接 drop 重建,否則舊資料會全部消失。
先把 version 的值遞增,再重新執行測試方法 testCreateDb(),即可觸發 onUpgrade。
建立 PersonService 業務類別:
package cn.class3g.service;
public class PersonService {
private DatabaseHelper dbHelper;
private Context context;
public PersonService(Context context) {
this.context = context;
dbHelper = new DatabaseHelper(context);
}
public void save(Person person) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// 使用占位符,避免 name = "T'om" 這類輸入造成語法錯誤
String sql = "insert into person(name,age) values(?,?)";
db.execSQL(sql, new Object[] { person.getName(), person.getAge() });
}
public void update(Person person, int id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
String sql = "update person set name=?,age=? where personid=?";
db.execSQL(sql, new Object[] { person.getName(), person.getAge(), id });
}
public Person find(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql = "select * from person where personid=?";
Cursor cursor = db.rawQuery(sql, new String[] { String.valueOf(id) });
if (cursor.moveToNext()) {
Person person = new Person();
person.setName(cursor.getString(cursor.getColumnIndex("name")));
person.setId(cursor.getInt(0));
person.setAge(cursor.getInt(2));
cursor.close(); // 關閉游標
return person;
}
return null;
}
public void delete(int id) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql = "delete from person where personid=?";
db.execSQL(sql, new Object[] { id });
}
public List<Person> getScrollData(int startIdx, int count) {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql = "select * from person limit ?,?";
Cursor cursor = db.rawQuery(sql,
new String[] { String.valueOf(startIdx),
String.valueOf(count) });
List<Person> list = new ArrayList<Person>();
while (cursor.moveToNext()) {
Person p = new Person();
p.setId(cursor.getInt(0));
p.setName(cursor.getString(1));
p.setAge(cursor.getInt(2));
list.add(p);
}
cursor.close();
return list;
}
public long getRecordsCount() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
String sql = "select count(*) from person";
Cursor cursor = db.rawQuery(sql, null);
cursor.moveToFirst();
long count = cursor.getInt(0);
cursor.close();
return count;
}
}
在測試類別 cn.class3g.db.PersonServiceTest 中補上對應的測試方法:
package cn.class3g.db;
public class PersonServiceTest extends AndroidTestCase {
public void testSave() throws Throwable {
PersonService service = new PersonService(this.getContext());
Person person = new Person();
person.setName("zhangxiaoxiao");
service.save(person);
Person person2 = new Person();
person2.setName("laobi");
service.save(person2);
Person person3 = new Person();
person3.setName("lili");
service.save(person3);
Person person4 = new Person();
person4.setName("zhaoxiaogang");
service.save(person4);
}
public void testUpdate() throws Throwable {
PersonService ps = new PersonService(this.getContext());
Person person = new Person("Ton", 122);
ps.update(person, 2);// 需先確認資料庫中 Ton 的 id
}
public void testFind() throws Throwable {
PersonService ps = new PersonService(this.getContext());
Person person = ps.find(2);
Log.i("TAG", person.toString());
}
public void testDelete() throws Throwable {
PersonService ps = new PersonService(this.getContext());
ps.delete(2);
}
public void testScroll() throws Throwable {
PersonService service = new PersonService(this.getContext());
List<Person> personList = service.getScrollData(3, 2);
Log.i("TAG", personList.toString());
}
public void testCount() throws Throwable {
PersonService service = new PersonService(this.getContext());
long count = service.getRecordsCount();
Log.i("TAG", String.valueOf(count));
}
}
android.database.sqlite.SQLiteException: Can't upgrade read-only database from version 0 to 1
這個錯誤大多是 SQL 語法有問題導致的,仔細檢查建表或更新用的 SQL 就能找到原因。另外別忘了用完了要關閉 Cursor,長時間累積會拖垮效能。