我正在尝试编写三种不同的方法来在 Android 的 SQLite 数据库中插入、更新和删除数据。到目前为止,我可以在数据库中插入数据,但我不明白如何在 SQL 中添加 where
子句。
这是我正在使用的代码:
更新方法:
public boolean updateSQL(String tableName,String key,String value){
return updateData(tableName,key,value);
}
private static boolean updateData(String tableName,String key,String value){
sqliteDb = instance.getWritableDatabase();
String where = "id=?";
ContentValues values = new ContentValues();
values.put(key, value);
values.put(key, value);
sqliteDb.update(tableName, values, where, null);
return true;
}
...我正在这样调用这个方法:
dbHelper.updateSQL("saved_codes", "code_id", "3");
//dbHelper is an instance to a custom DatabaseHelper class.
.. 和删除方法:
public boolean deleteSQL(String tableName,String key,String value){
return deleteData(tableName,key,value);
}
private static boolean deleteData(String tableName,String key,String value) {
sqliteDb = instance.getWritableDatabase();
ContentValues values = new ContentValues();
String where = null;
String[] whereArgs = null;
values.put(key, value);
values.put(key, value);
sqliteDb.delete(tableName, where, whereArgs);
return true;
}
我知道字符串 where
和 whereArgs
是 null
,但实际上我不明白如何添加它们。
我不希望有人为我编写代码,但欢迎提供一些好的意见、建议甚至来自 Internet 的示例。
最佳答案
你需要 whereArgs
String where = "id=?";
类似的东西:
sqliteDb.update(tableName, values, where, new String[] {"42"});
其中 42 是要更新的行的 _id。也更喜欢 BaseColumns._ID 而不是“id”。
关于Android 插入/更新/删除 SQLite 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7390424/