В проекте, над которым я работал, есть много похожих блоков кода.
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().
Я не могу понять поведение. Запрос выглядит довольно вменяемым и на самом деле работает. Значения правильно отформатированы в соответствии со схемой. Что еще может вызвать это?
try pstmt.executeUpdate();
вместо pstmt.executeUpdate(insertQuery);
pstmt.executeUpdate(); Нет необходимости в параметрах
или вы должны проверить типы параметров для вас sql
pstmt.executeUpdate();
вместоpstmt.executeUpdate(insertQuery);