在添加行之前检查SQLite数据库中的重复项

时间:2012-12-04 21:11:49

标签: android sqlite

我正在尝试使用以下代码向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)

1 个答案:

答案 0 :(得分:2)

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

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

(如果只有值发生变化,你真的想要用同一个键插入另一条记录吗? 或者您是否愿意更新该记录?)