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