1

我正在尝试使用以下代码在 android 中的数据库中添加一行,但我想确保该行不存在,我该怎么做?

void addKey(String key, String value, String table) {

            SQLiteDatabase db = this.getWritableDatabase();

            ContentValues values = new ContentValues();
            values.put(KEY_KEY, key);
            values.put(KEY_VALUE, value);

            // Inserting Row
            db.insert(table, null, values);
            db.close(); // Closing database connection          
    }

我尝试使用以下代码,但无法正常工作

public boolean check(String key, String value, String table) {
        SQLiteDatabase db = this.getWritableDatabase();
        String sql = "select * from " + table + " where key= " + key + " and value= " + value;
        Cursor cur = db.rawQuery( sql, new String[0] );

        if(cur.getCount() == 0)
        {
            cur.close();
            db.close();
            return false;
        }

        else{
            cur.close();
            db.close();
            return true;
        }

    }

错误:

12-04 16:34:46.867: E/AndroidRuntime(2743): Caused by: android.database.sqlite.SQLiteException: no such column: hi: , while compiling: select * from tableOne where key= hi and value= baby
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteCompiledSql.compile(SQLiteCompiledSql.java:92)
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:65)
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:83)
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:49)
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:42)
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1428)
12-04 16:34:46.867: E/AndroidRuntime(2743):     at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1396)
4

1 回答 1

2

您必须在 SQL 中正确格式化字符串(这涉及引用字符串本身以及字符串中的任何引号),或者使用参数将字符串传递到数据库中:

String sql = "SELECT * FROM " + table + " WHERE key=? AND value=?";
Cursor cur = db.rawQuery(sql, new String[] { key, value });

如果只有值改变,你真的要插入另一条具有相同键的记录吗?还是您更愿意更新该记录?

于 2012-12-04T21:36:15.627 回答