public void addFavourite(User user,Winkel winkel){
ContentValues values = new ContentValues();
values.put(COLUMN_NAME,winkel.getNaam());
values.put(COLUMN_POSTCODE, winkel.getPostcode());
values.put(COLUMN_DEELGEMEENTE, winkel.getDeelGemeente());
values.put(COLUMN_GEMEENTE, winkel.getGemeente());
values.put(COLUMN_ADRES, winkel.getAdres());
Log.d("lol",user.getUserName()); // Log is succesfull
values.put(COLUMN_USERNAME, user.getUserName());
SQLiteDatabase db = this.getWritableDatabase();
db.insert(TABLE_FAVOURITES, null, values);
db.close();
}
public void deleteFavourite(User user,Winkel winkel){
String selectQuery = "DELETE FROM " + TABLE_FAVOURITES + " WHERE " + COLUMN_USERNAME+"=" + user.getUserName() + " AND " + COLUMN_NAME + "=" + winkel.getNaam();
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(selectQuery);
db.close();
}
String CREATE_FAVOURITES_TABLE = "CREATE TABLE IF NOT EXISTS " +
TABLE_FAVOURITES + "("
+ COLUMN_ID2 + " INTEGER PRIMARY KEY,"
+ COLUMN_NAME + " TEXT,"
+ COLUMN_POSTCODE + " INTEGER,"
+ COLUMN_DEELGEMEENTE + " TEXT,"
+ COLUMN_GEMEENTE + " TEXT,"
+ COLUMN_ADRES + " TEXT,"
+ COLUMN_USERNAME + " TEXT, "
+ "FOREIGN KEY(" + COLUMN_USERNAME+ ") REFERENCES "
+ TABLE_USERS + "(username) " + ")";
db.execSQL(CREATE_FAVOURITES_TABLE);
尝试删除收藏夹时出现Sql异常:
android.database.sqlite.SQLiteException: no such column: Gebruikersnaam (code 1): , while compiling: DELETE FROM favorieten WHERE username=Gebruikersnaam AND naam=EUROCITY
注意:所以我假设在添加收藏夹时出现问题,并且用户名实际上没有添加到表中,或者我的create table语句中出现了错误,或者出现了错误在我的删除查询中。但我无法弄明白。为什么这不起作用?
答案 0 :(得分:2)
您需要将字符串括在单引号中 I.e。:WHERE username =' Gebruikersnaam' AND naam =' EUROCITY'
绑定参数将更好地工作
如果字符串包含一个或多个撇号("'"
=> "''"
),它们还会将单引号加倍。
所以你不必手动更换它们。
在你的情况下,它是这样的:
// Put your parameters in this array (no matter if they are numeric types
// because the SQL statement is a string anyway),
// in the exact order of appearance in your query or SQL command
String[] strParams = new String[]{user.getUserName(), winkel.getNaam()};
// Your modified SQL command with the parameter placeholders (?)
String selectQuery = "DELETE FROM " + TABLE_FAVOURITES +
" WHERE " + COLUMN_USERNAME + " = ? AND " + COLUMN_NAME + " = ?";
SQLiteDatabase db = this.getWritableDatabase();
// Use this execSQL() syntax
db.execSQL(selectQuery, strParams);
db.close();