編輯:關於 Android 程式設計
前面幾章我們分別學習了 SharedPreferences 屬性文件存儲、內部存儲與外部存儲。這一章來看看 Android 內建的輕量級數據庫——SQLite。
SQLiteDatabase 本身只是一個數據庫操作類,真正要開展工作還需要一個 SQLiteOpenHelper 來幫忙創建與打開。而 SQLiteOpenHelper 是抽象類,使用時必須定義子類並覆寫相應的抽象方法。
常用方法:
SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version):構造方法,指明數據庫名與版本號close():關閉數據庫getReadableDatabase():以只讀方式創建或打開數據庫getWritableDatabase():以讀寫方式創建或打開數據庫onCreate(SQLiteDatabase db):創建數據表(抽象)onOpen(SQLiteDatabase db):打開數據庫onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion):更新數據表(抽象)三個關鍵回調:
onCreate():第一次使用數據庫時調用,用來建表。注意它不是在實例化 Helper 對象時調用,而是在第一次調用 getReadableDatabase() 或 getWritableDatabase() 時才會觸發。onUpgrade():數據庫版本號提升時調用。通常在此刪除舊表,然後調用 onCreate() 重新建表。onOpen():數據庫打開時調用,一般不需要覆寫。佈局文件:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="108dp"
android:text="建立數據庫" />
</RelativeLayout>
讓一個類繼承 SQLiteOpenHelper 並覆寫方法:
public class SqlIteOpenHelper extends SQLiteOpenHelper {
public static final String DBNAME = "flyou"; // 數據庫名稱
public static final int VERSION = 2; // 數據庫版本
public static final String TABLENAME = "user_info"; // 數據表名稱
public SqlIteOpenHelper(Context context) {
super(context, DBNAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE " + TABLENAME + " ("
+ "id INTEGER PRIMARY KEY ,"
+ "name VARCHAR(50) NOT NULL ,"
+ "birthday DATE NOT NULL)";
db.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLENAME);
onCreate(db);
}
}
只要調用一次 getWritableDatabase(),SQLite 就會在應用的 /data/data/<包名>/databases/ 目錄下生成 flyou 這個數據庫文件,並執行 onCreate() 建表。

數據庫文件生成後的位置:

Helper 代碼與上一節相同,另寫一個專門的操作類來封裝數據訪問:
public class Operator {
private SQLiteDatabase db = null;
public Operator(SQLiteDatabase db) {
this.db = db;
}
/** 數據插入 */
public void insert(String name, String birthday) {
String sql = "insert into " + SqlIteOpenHelper.TABLENAME
+ " (name,birthday) Values(?,?)";
Object args[] = { name, birthday };
db.execSQL(sql, args);
}
/** 數據更新 */
public void upDate(int id, String name, String birthday) {
String sql = "update " + SqlIteOpenHelper.TABLENAME
+ " set name=?,birthday=? where id=?";
Object args[] = { id, name, birthday };
db.execSQL(sql, args);
}
/** 數據刪除 */
public void delete(int id) {
String sql = "delete from " + SqlIteOpenHelper.TABLENAME + " where id=?";
Object args[] = { id };
db.execSQL(sql, args);
}
}
execSQL(sql, args) 這種帶占位符的寫法要優於字符串拼接——既能規避 SQL 注入,也能正確處理引號等特殊字符。
操作完成後把數據庫文件拉出來查看:

除了寫 SQL,SQLiteDatabase 還提供了 insert()、update()、delete() 這組方法,配合 ContentValues 使用:
public class Operator {
private SQLiteDatabase db = null;
public Operator(SQLiteDatabase db) {
this.db = db;
}
/** 插入數據 */
public void insert(String name, String birthday) {
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("birthday", birthday);
db.insert(Helper.TABLENAME, null, cv);
}
/** 更新數據 */
public void upDate(String name, String birthday, int id) {
ContentValues cv = new ContentValues();
cv.put("name", name);
cv.put("birthday", birthday);
String whereClause = "id=?";
String whereArgs[] = { String.valueOf(id) };
db.update(Helper.TABLENAME, cv, whereClause, whereArgs);
}
/** 刪除數據 */
public void delete(int id) {
String whereClause = "id=?";
String whereArgs[] = { String.valueOf(id) };
db.delete(Helper.TABLENAME, whereClause, whereArgs);
}
}
Activity 中通過按鈕觸發:
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
helper = new Helper(MainActivity.this);
database = helper.getWritableDatabase();
new Operator(database).insert("房澤龍", "1992-03-18");
database.close();
}
});
運行效果與導出後的數據:


由於點擊了多次插入,可以看到裡面已經累積了多條數據。
查詢結果由 Cursor 封裝,常用方法有:
close():關閉查詢getCount():返回查詢到的數據總量getColumnCount():返回結果的列數getColumnNames() / getColumnName(int):獲取列名isAfterLast() / isBeforeFirst() / isFirst() / isLast() / isClosed():指針位置判斷moveToFirst() / moveToLast() / moveToNext() / moveToPrevious():指針移動getXxx(int columnIndex):按列索引取值,如 getInt()、getString()遍歷結果集的標準寫法:
for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {
// 循環體
}
完整示例的佈局:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="插入數據" />
<Button android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button1"
android:layout_alignBottom="@+id/button1"
android:layout_centerHorizontal="true"
android:text="更新數據" />
<Button android:id="@+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/button2"
android:layout_alignBottom="@+id/button2"
android:layout_toRightOf="@+id/button2"
android:text="刪除數據" />
<Button android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button1"
android:layout_alignRight="@+id/button3"
android:layout_below="@+id/button1"
android:text="全部查詢" />
<Button android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignRight="@+id/button4"
android:layout_below="@+id/button4"
android:text="模糊查詢" />
<EditText android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/button2"
android:layout_below="@+id/button4"
android:ems="10" >
<requestFocus />
</EditText>
<ListView android:id="@+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/button5"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
操作類中新增兩個查詢方法:
/** 查找全部數據 */
public List<String> findAll() {
List<String> all = new ArrayList<String>();
String columns[] = { "id", "name", "birthday" };
Cursor result = this.db.query(Helper.TABLENAME, columns, null, null, null, null, null);
for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {
all.add("[" + result.getInt(0) + "]--"
+ result.getString(1) + "--" + result.getString(2));
}
result.close();
return all;
}
/** 模糊查詢 */
public List<String> findBy(String keyword) {
List<String> all = new ArrayList<String>();
String sql = "select * from " + Helper.TABLENAME
+ " where name like ? or birthday like ? or id like ?";
String contexstr[] = {
"%" + keyword + "%",
"%" + keyword + "%",
"%" + keyword + "%"
};
Cursor result = this.db.rawQuery(sql, contexstr);
for (result.moveToFirst(); !result.isAfterLast(); result.moveToNext()) {
all.add("[" + result.getInt(0) + "]--"
+ result.getString(1) + "--" + result.getString(2));
}
result.close();
return all;
}
這裡演示了兩種查詢方式:db.query() 是方法參數式 API,db.rawQuery() 則直接吃 SQL 語句。前者更規範,後者更靈活——模糊查詢這種多字段 OR 的場景用 rawQuery 寫起來清爽不少。兩者都支持 ? 占位符。
界面展示:



close(),這不是可選項——Cursor 持有的是游標資源,不及時關閉會導致內存洩漏,量大了還會拋 CursorLeaked 相關異常。更好的做法是使用 try-with-resources(Cursor 實現了 Closeable)。onClick() 裡,真實項目中應該放到子線程或 AsyncTask / 線程池裡,否則數據量大時會 ANR。onUpgrade() 直接 DROP 重建,這會清空用戶數據。正式產品中應該寫遷移邏輯(ALTER TABLE ADD COLUMN、或新建表 + 拷貝數據 + 改名)。limit offset,事務用 beginTransaction() / setTransactionSuccessful() / endTransaction(),注意事務要在 endTransaction() 之前設置成功標記。另外,如果數據量較大或需要複雜的關係建模,可以考慮 ORM 框架(Room、GreenDAO)來減少樣板代碼;Room 還自帶了編譯期 SQL 校驗與與 LiveData / Flow 的響應式集成。
下節預告:意圖 Intent
小米雲服務變灰無法點擊?開啟自動同步就能恢復
小米雲服務頁面變灰、無法點擊,通常是自動同步未開啟。下拉通知欄,長按自動同步圖示,進入設定後開啟同步,再回到雲服務即可正常使用。
城市列表實作:依拼音首字母排序
這次要完成的是一個常見需求:把城市名稱讀出來,轉成拼音、依首字母排序,再用 ListView 呈現。以下拆解每一步。 一、主佈局檔 <LinearLayout x
Android LRU 緩存演算法學習筆記(一):源碼透視
在行動應用開發中,我們經常會遇到大數據量的訪問場景,這時通常得權衡幾件事:一是手機記憶體有限,還要保證應用反應流暢;二是盡量降低流量消耗,否則體驗再好,使用者也可能毫不猶
Android Intent 傳遞對象的兩種方式:Serializable 與 Parcelable 全面對比
頁面之間傳幾個基本類型參數很簡單,一旦要傳整個對象,就得靠 Bundle 了。常用做法有兩條路:Bundle.putSerializable(Key, Object) 和