Android 插入/更新/删除 SQLite 查询

标签 android sqlite

我正在尝试编写三种不同的方法来在 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;
}

我知道字符串 wherewhereArgsnull,但实际上我不明白如何添加它们。 我不希望有人为我编写代码,但欢迎提供一些好的意见、建议甚至来自 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/

相关文章:

android - 展开 FloatinfActionMenu 时如何设置外部颜色?

android - 如何在 Android Studio 中使用 retrofit2 获取 json 日志?

Android:在创建数据库时仅在数据库中插入一次行

c# - 获取最后插入的 ID

sqlite - 在 WinRT 应用程序中使用 SQLite 时出现异常

android - 当 NavHostFragment 包含非 ScrollView 时,CoordinatorLayout 作为顶级装饰

android - 获取Json数组中的数据并发送给服务器

android - 是否可以创建一个项目比 json 多的模型?

android - 如何在 SQLite 中设置时区?

objective-c - 如何在 Objective-C 中使用 SQLite3 中的保存点