存在语法错误:
线程“主”中的异常java.sql.SQLSyntaxErrorException:您的SQL语法错误;检查与您的手册相对应的手册MySQL服务器版本,用于在'WHERE id = 1'附近使用的正确语法第1行com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)在com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)在com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)在com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1335)在com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2108)在com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1245)在DaoImplement.editCar(DaoImplement.java:108)在Main.main(Main.java:46)
使用代码:
public void editCar(Car editedCar) throws SQLException { final String EDIT_CAR = String.format("UPDATE %s SET " + "carVin = %d, " + "carBrand = '%s', " + "carModel = '%s', " + "carDateOfProduction = '%s', " + "carColour = '%s', ", "WHERE id = %d;", tableName, editedCar.getCarVin(), editedCar.getCarBrand(), editedCar.getCarModel(), editedCar.getCarDateOfProduction(), editedCar.getCarColour(), editedCar.getId()); statement.executeUpdate(EDIT_CAR); System.out.println("Samochód został nadpisany"); }
我看不到“ WHERE ID =%d;”中的位置是语法错误。有人知道我该如何解决? :)
我刚刚开始学习Java,我在网上看了答案,但似乎没有任何反应。语法错误:线程“ main”中的异常java.sql.SQLSyntaxErrorException:您的....>
首先,删除EDIT_CAR字符串中"WHERE"
关键字之前的逗号(这是语法问题)。其次,我建议如下修改您的方法(假设您的数据库连接为conn
,并且Car属性carDateOfProduction
的类型为java.sql.Date
):
public void editCar(Car editedCar) throws SQLException {
final String EDIT_CAR = String.format("UPDATE %s SET "
+ "carVin = ?, "
+ "carBrand = ?, "
+ "carModel = ?, "
+ "carDateOfProduction = ?, "
+ "carColour = ? ",
"WHERE id = ?",
tableName);
PreparedStatement stmt = conn.prepareStatement(EDIT_CAR);
stmt.setInt(1, editedCar.getCarVin());
stmt.setString(2, editedCar.getCarBrand());
stmt.setString(3, editedCar.getCarModel());
stmt.setDate(4, editedCar.getCarDateOfProduction());
stmt.setString(5, editedCar.getCarColour());
stmt.setInt(1, editedCar.getId());
stmt.executeUpdate();
System.out.println("Samochód został nadpisany");
}