2016-07-30 42 views
1
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異常:SQLlite - 在DELETE命令沒有這樣的列

android.database.sqlite.SQLiteException: no such column: Gebruikersnaam (code 1): , while compiling: DELETE FROM favorieten WHERE username=Gebruikersnaam AND naam=EUROCITY 

注:所以我假設要麼添加喜歡的什麼是錯的,而實際上用戶名沒有被添加到表中,或者在create table語句中出現錯誤,或者在我的deletequery中出現錯誤。我無法弄清楚。爲什麼這不起作用?

+1

您需要附上字符串單引號。 I.e .:'WHERE username ='Gebruikersnaam'AND naam ='EUROCITY'' –

+2

你忘了引用你的價值。但實際上你應該使用Prepared Statements –

+0

@juergend是的,綁定的參數效果更好。在包含一個或多個撇號的字符串的情況下,他們還會考慮將單引號加倍(''''>'''') –

回答

1

你需要用單引號括起你的字符串。
即:用戶名='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(); 
相關問題