SQLiteDatabase類暴露了特定的方法,如insert、delete和update等方法,這些方法包裝了執行這些動作所需的SQL語句。盡管如此,execSQL方法允許你在數據庫表上執行任何有效的SQL語句,而這些動作就是你想要手動執行的。
在任何時候,如果你修改了底層數據庫的值,你都應該調用任一在當前表上瀏覽的Cursor的refreshQuery方法。
插入新行
為了創建一個新行,構造一個ContentValues對象,並使用它的put方法來為每一列提供值。通過在目標數據庫對象上調用insert方法,並將ContentValues對象傳入方法中來插入一個新行——需要有表的名稱——如下面的片段所示:
// Create a new row of values to insert.
ContentValues newValues = new ContentValues();
// Assign values for each row.
newValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
// Insert the row into your table
myDatabase.insert(DATABASE_TABLE, null, newValues);
更新行
更新行也需要通過ContentValues來實現。
創建一個新的ContentValues對象,使用put方法來為每一個你想更新的列指定新的值。調用數據庫對象的update方法,傳入表名和更新的ContentValues對象,一個where語言來指明哪些行需要更新。
更新的處理在下面的片段中有演示:
// Define the updated row content.
ContentValues updatedValues = new ContentValues();
// Assign values for each row.
updatedValues.put(COLUMN_NAME, newValue);
[ ... Repeat for each column ... ]
String where = KEY_ID + “=” + rowId;
// Update the row with the specified index with the new values.
myDatabase.update(DATABASE_TABLE, updatedValues, where, null);
刪除行
為了刪除一行,你可以在數據庫對象上簡單調用delete方法,指定表名和一個where語句來指明那些行你想要刪除,如下面的代碼所示:
myDatabase.delete(DATABASE_TABLE, KEY_ID + “=” + rowId, null);
