Java 下面的问题是什么
我已经编写了一个SQLite查询,在“=”附近出现以下错误: 编译时出现语法错误(代码1):Java 下面的问题是什么,java,android,sql,sqlite,Java,Android,Sql,Sqlite,我已经编写了一个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.getReadableDatab
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;
}
您的查询没有空格。改为
String selectQuery = "SELECT COUNT(product_id)" +
" FROM " + TABLE_CART +
" WHERE product_id = " + product_id + " AND user_id = " + user_id;
在这里,我在
之前添加了一个空格,它来自和WHERE
,如果您只需要使用计数,可能会更好
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注入,您可以使用:
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();
它在SELECT COUNT(product\u id)
之后缺少空格字符。问题不在于它与实际的sqlite语句之间的空格。正确,但是像这样的模板是最简单的黑客攻击方法之一。你说这个的失败让我给了你一个-1。有没有什么原因让它不断返回一的值,不是实际的计数@azaro@GeorgeMujuru似乎两个product\u id
或user\u id
中的一个是TABLE\u CART
的主键,主键应该是唯一的,因为您只得到一个结果,我建议您检查查询等待的逻辑,但这是正确的,我只想看到的是,是否已经存在具有产品和用户id的记录。@GeorgeMujuru当您在sql编辑器中使用它时,您会得到什么?