从sql表值中减去scanner值

oprakyz7  于 2021-07-24  发布在  Java
关注(0)|答案(1)|浏览(357)

我试图从表值中减去扫描仪输入。这是我table的截图:

我的代码是这样的:

  1. String url = "jdbc:mysql://localhost:3306/Project";
  2. String username = "x";
  3. String password = "y";
  4. try {
  5. Scanner scanner = new Scanner(System.in);
  6. System.out.println("What would you like to buy?");
  7. int purchase_id = scanner.nextInt();
  8. System.out.println("How many would you like to purchase?");
  9. int quantity = scanner.nextInt();
  10. Connection conn = DriverManager.getConnection(url, username, password);
  11. Statement myStmt = conn.createStatement();
  12. String sql = "update seattleBranch set inventory = " + quantity + "where item_id = 001";
  13. myStmt = conn.prepareStatement(sql);
  14. ((PreparedStatement) myStmt).executeUpdate();
  15. }
  16. catch (SQLException e) {
  17. e.printStackTrace();
  18. }
  19. }

我的代码的输出是:

  1. java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'item_id = 001' at line 1
  2. at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
  3. at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
  4. at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
  5. at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
  6. at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
  7. at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
  8. at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
  9. at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
  10. at branchComms.main(branchComms.java:27)

以下是我希望我的表减去100(我的扫描仪输入量)后的样子:

我不确定为什么减去我的扫描器变量(数量)不工作,我将感谢任何更正我的代码。

yeotifhr

yeotifhr1#

查询中缺少 where 部分,应该是这样的:

  1. String sql = "update seattleBranch set inventory = " + quantity + " where item_id = 001";

相关问题