我已经编写了一个SQLite查询,并且在“ =”附近出现了以下错误:
语法错误(代码1):,正在编译:
SELECT COUNT(product_id)FROM cartWHERE product_id = ?2593 AND user_id = ?138
查询如下所示。我认为我的查询是正确的
public int countItems(Integer product_id, Integer user_id)
{
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor;
String selectQuery = "SELECT COUNT(product_id)" +
"FROM " + TABLE_CART +
"WHERE product_id = " + product_id + " AND user_id = " + user_id;
try
{
cursor = db.rawQuery(selectQuery, null);
cursor.close();
return cursor.getCount();
} catch (SQLException ex)
{
ex.printStackTrace();
}
return 0;
}
答案 0 :(得分:4)
永远不要在查询中使用串联,而是会出现语法错误或SQL注入,而可以使用:
SQLiteDatabase db = this.getReadableDatabase();
SQLiteStatement stmt = db.compileStatement("SELECT COUNT(product_id) FROM " + TABLE_CART +
" WHERE product_id = ? AND user_id = ?");
stmt.bindInt(1, product_id);
stmt.bindInt(2, user_id);
long count = stmt.simpleQueryForLong();
答案 1 :(得分:2)
您的查询没有空格。更改为
String selectQuery = "SELECT COUNT(product_id)" +
" FROM " + TABLE_CART +
" WHERE product_id = " + product_id + " AND user_id = " + user_id;
在这里,我在FROM
和WHERE
之前添加了一个空格。
答案 2 :(得分:2)
如果您只需要计数,则最好使用
public int countItems(Integer product_id, Integer user_id) {
SQLiteDatabase db = this.getReadableDatabase();
String query = "SELECT COUNT(product_query) FROM " + TABLE_CART + " WHERE product_id=? AND user_id=?";
String[] whereValues = new String[] {String.valueOf(product_id), String.valueOf(user_id)};
return DatabaseUtils.longForQuery(db, query, whereValues);
}
通常,在SQL查询中仅对变量进行字符串连接被认为是不好的做法,并且很危险。阅读有关此主题的更多信息:SQL injection