我一直在从事的项目中有许多类似的代码块。
DBConnector db = new DBConnector();
Connection conn = db.connect();
String insertQuery = "INSERT INTO track_item_result (tirTrackItemId, tirNodeId, tirDetailId, tirResultString, tirResultValue, tirStatus) " + "VALUES (?,?,?,?,?,?)";
PreparedStatement pstmt = conn.prepareStatement(insertQuery, Statement.RETURN_GENERATED_KEYS);
pstmt.setInt(1, this.trackItem.getId());
pstmt.setInt(2, this.node.getId());
pstmt.setInt(3, this.tirDetailId);
pstmt.setString(4, this.tirResultString);
pstmt.setString(5, this.tirResultValue);
pstmt.setString(6, this.tirStatus);
System.out.println(pstmt.toString());
pstmt.executeUpdate(insertQuery);
ResultSet generatedKeys = pstmt.getGeneratedKeys();
我在上面的代码的最后3行打印了查询,这是格式正确的SQL语句。
com.mysql.cj.jdbc.ClientPreparedStatement: INSERT INTO track_item_result (tirTrackItemId, tirNodeId, tirDetailId, tirResultString, tirResultValue, tirStatus) VALUES (3,15,0,'<EOL><EOL><EOL><EOL>','-1','F')
如果我直接在MySQL客户端上复制粘贴此生成的查询,它似乎可以正常工作。但是在项目中,它会引发可怕的 SQL语法错误
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 '?,?,?,?,?,?)' at line 1
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:118)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:95)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1393)
at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2353)
at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1303)
at com.example.myproject.models.TrackItemResult.insertInDb(TrackItemResult.java:98)
at com.example.myproject.healthcheck.TrackItemRunnable.run(TrackItemRunnable.java:86)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:308)
在此行TrackItemResult.insertInDb(TrackItemResult.java:98)是pstmt.executeUpdate()行。
我无法理解该行为。该查询看起来很理智,并且可以正常工作。值已根据架构正确格式化。还有什么可能导致这种情况?
答案 0 :(得分:1)
尝试用pstmt.executeUpdate();
代替pstmt.executeUpdate(insertQuery);
答案 1 :(得分:1)
pstmt.executeUpdate();不需要参数
或者您应该为您的SQL检查参数类型