【问题标题】:Unable to solve a syntax error near WHERE in sqlite, android无法解决sqlite,android中WHERE附近的语法错误
【发布时间】:2019-06-30 11:57:52
【问题描述】:

我有一个带有 SQLite 语句的字符串,我想像这样执行它..

String query = "UPDATE Inventory SET ProductName =" 
+ product.getProductName() + ", InStock =" + product.getProductInStock()
+ ", CostPrice =" + product.getProductCostPrice() + ",SellingPrice =" 
+ product.getProductSellingPrice() + ", Description =" 
+ product.getProductDescription() + " WHERE rowid =" 
+ String.valueOf(Integer.parseInt(rowId) + 1);

db.execSQL(query);

我有一个名为 Product 的 POJO 类。 rowid 是一个内置变量,对吗?我试了大写还是不行。

我收到以下错误

E/SQLiteLog: (1) near "WHERE": syntax error

【问题讨论】:

  • 什么是String.valueOf(Integer.parseInt(rowId) + 1)?或者你希望它做什么?
  • @tomerpacific,结尾部分是字符串,不需要。
  • @forpas rowId 是一个字符串,但它包含一个数字,我将其转换为数字然后加 1,后来我将其转换回字符串,因为它是字符串变量的一部分。
  • 1) 将query的值打印出来会更容易发现问题。将其添加到问题中。 2)您应该使用PreparedStatement 而不是使用“字符串抨击”来构造查询。
  • (我敢打赌,产品描述是一个字符串,这很混乱,因为您在 SQL 字符串抨击中没有在它周围加上引号。)

标签: java android sqlite android-sqlite


【解决方案1】:

在您的代码中,您将值设置为 text 列而不使用单引号。
这可能是代码的问题之一。
推荐的更新方式是使用ContentValues,这也是sql-injection安全:

ContentValues cv = new ContentValues();
cv.put("ProductName", product.getProductName());
cv.put("InStock", product.getProductInStock());
cv.put("CostPrice", product.getProductCostPrice());
cv.put("SellingPrice", product.getProductSellingPrice());
cv.put("Description", product.getProductDescription());
int result = db.update("Inventory", cv, "rowid = ?", new String[] {String.valueOf(Integer.parseInt(rowId) + 1)});

变量result 将包含更新的行数。
我不确定那个值:

String.valueOf(Integer.parseInt(rowId) + 1)

但如果你已经测试过就可以了。

【讨论】:

  • 非常感谢!我实际上并没有发现错误是什么,但是内容值方法运行良好。当我从数据库中检索产品时,我使用了相同的String.valueOf(Integer.parseInt(rowId) + 1),它工作正常,所以我认为这不是问题。
  • 如果它工作得很好。使用 ContentValues 而不是连接 sql 部分。这既简单又安全。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-17
  • 2015-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多