Java 从sql表值中减去扫描程序值
我试图从表值中减去扫描仪输入。这是我桌子的截图: 我的代码是这样的:Java 从sql表值中减去扫描程序值,java,mysql,sql,java.util.scanner,Java,Mysql,Sql,Java.util.scanner,我试图从表值中减去扫描仪输入。这是我桌子的截图: 我的代码是这样的: String url = "jdbc:mysql://localhost:3306/Project"; String username = "x"; String password = "y"; try { Scanner scanner = new Scanner(System.in); Syst
String url = "jdbc:mysql://localhost:3306/Project";
String username = "x";
String password = "y";
try {
Scanner scanner = new Scanner(System.in);
System.out.println("What would you like to buy?");
int purchase_id = scanner.nextInt();
System.out.println("How many would you like to purchase?");
int quantity = scanner.nextInt();
Connection conn = DriverManager.getConnection(url, username, password);
Statement myStmt = conn.createStatement();
String sql = "update seattleBranch set inventory = " + quantity + "where item_id = 001";
myStmt = conn.prepareStatement(sql);
((PreparedStatement) myStmt).executeUpdate();
}
catch (SQLException e) {
e.printStackTrace();
}
}
我的代码的输出是:
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
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1347)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
at branchComms.main(branchComms.java:27)
以下是减去100(我的扫描仪输入量)后我希望我的表的外观:我不确定为什么减去扫描器变量(数量)不起作用,我希望对我的代码进行任何更正。您在
where
部分前面的查询中缺少一个空格,应该是这样的:
String sql = "update seattleBranch set inventory = " + quantity + " where item_id = 001";
SQL语句应该类似于
UPDATE seattleBranch SET inventory=inventory-quantity,其中item\u id=purchase\u id