我正在使用 Java Swing 应用程序来更新 Mysql 表中的列。这是我的代码(部分)
String qunty = txtWithdraw.getText();
String partno = txtNo.getText();
int qty = Integer.parseInt(qunty);
con = DriverManager.getConnection(url + db, "username", "password");
Statement st = con.createStatement();
String sell = "update Store_info_table set qnty_received = qnty_received - " + qty + "where Part_number = '" + partno + "'";
st.executeUpdate(sell);
我得到的异常是:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: 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 'Part_number = 'DF6534'' at line 1
我想更新 qnty_received 字段,使其等于原始值减去用户传递的值,即 (int qty)。我犯了什么错误?
最佳答案
在where前加一个空格:
" where Part_number = '" + partno + "'";
作为一种好的做法,我建议您使用 PreparedStatement
并使用相同的参数设置您的参数。动态连接参数可能会强制数据库引擎每次都解析新的 SQL 语句。
A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.
关于java - Mysql数据库更新字段时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12056952/