2014-03-05 48 views
2

我遇到了使用SQLite的問題。當我試圖生我在這裏的查詢是我有錯誤。「@domain」附近的語法錯誤SQLite

03-05 11:40:54.916: E/AndroidRuntime(6136): Caused by: android.database.sqlite.SQLiteException: near "@domain": syntax error (code 1): , while compiling: SELECT * FROM shopping_list WHERE shopping_list_owner = [email protected] 

這裏是功能的原始查詢:

public List<ShoppingListModel> getAllShoppingListByOwner(String owner) { 
    List<ShoppingListModel> shoppingList = new ArrayList<ShoppingListModel>(); 
    String selectQuery = "SELECT * FROM " + TABLE_SHOPPING_LIST + " WHERE " + SHOPPING_LIST_OWNER + " = " + owner; 

    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor cursor = db.rawQuery(selectQuery, null); 
    if (cursor.moveToFirst()) { 
     do { 
      ShoppingListModel list = new ShoppingListModel(cursor.getString(cursor.getColumnIndex(SHOPPING_LIST_NAME)), 
                  cursor.getInt(cursor.getColumnIndex(SHOPPING_LIST_ID)), 
                  cursor.getString(cursor.getColumnIndex(SHOPPING_LIST_DATE_CREATION)), 
                  cursor.getString(cursor.getColumnIndex(SHOPPING_LIST_OWNER))); 
      shoppingList.add(list); 
     } while (cursor.moveToNext()); 
    } 
    return shoppingList; 
} 

ownerString包含像這樣=> 「[email protected]

回答

6

SQL字符串文字需要在''單引號。

但是,最好使用?佔位符和綁定args作爲文字:

String selectQuery = "SELECT * FROM " + TABLE_SHOPPING_LIST + " WHERE " + SHOPPING_LIST_OWNER + " = ?"; 

Cursor cursor = db.rawQuery(selectQuery, new String[] { owner }); 
1

所有者應被引號包圍。

String selectQuery = "SELECT * FROM " + TABLE_SHOPPING_LIST + " WHERE " + SHOPPING_LIST_OWNER + "=\'" + owner + '\''; 
2

嘗試像這樣

public List<ShoppingListModel> getAllShoppingListByOwner(String owner) { 
    List<ShoppingListModel> shoppingList = new ArrayList<ShoppingListModel>(); 
    String selectQuery = "SELECT * FROM " + TABLE_SHOPPING_LIST + " WHERE " + SHOPPING_LIST_OWNER + " = " + "'"+owner+"'"; 

    SQLiteDatabase db = this.getWritableDatabase(); 
    Cursor cursor = db.rawQuery(selectQuery, null); 
    if (cursor.moveToFirst()) { 
     do { 
      ShoppingListModel list = new ShoppingListModel(cursor.getString(cursor.getColumnIndex(SHOPPING_LIST_NAME)), 
                  cursor.getInt(cursor.getColumnIndex(SHOPPING_LIST_ID)), 
                  cursor.getString(cursor.getColumnIndex(SHOPPING_LIST_DATE_CREATION)), 
                  cursor.getString(cursor.getColumnIndex(SHOPPING_LIST_OWNER))); 
      shoppingList.add(list); 
     } while (cursor.moveToNext()); 
    } 
    return shoppingList; 
} 
1

由於您的變量所有者是String類型的,你需要添加打開和關閉'單引號。使用您的查詢方式,

String selectQuery = "SELECT * FROM " + TABLE_SHOPPING_LIST + 
" WHERE " + SHOPPING_LIST_OWNER + " ='" + owner + "'";