【发布时间】:2013-08-14 14:19:51
【问题描述】:
我有以下查询用于准备好的语句:
INSERT INTO mytable (`col1_id`, `col2`, `col3`, `col4`, `col5`, `col6`, `col7`) VALUES(?, ?, ?, ?, ?, ?, ?)" +
" ON DUPLICATE KEY UPDATE `col1`=?, `col2`=?, `col3`=?, `col4=?, `col5`=?, `col6`=?, `col7`=?;
col1_id 是主键。
Java 简化代码(省略了 try/catch,遍历我的集合以向批处理中添加更多语句等):
Connection connection = null;
PreparedStatement statement = null;
String insertAdwordsQuery = DatabaseStatements.InsertAdwordsData(aProjectID);
connection = MysqlConnectionPool.GetClientDbConnection(aUserID);
connection.setAutoCommit(false);
statement = connection.prepareStatement(insertAdwordsQuery);
statement.setInt(1, x);
statement.setDouble(2, x);
statement.setLong(3, x);
statement.setLong(4, x);
statement.setDouble(5, x);
statement.setString(6, x);
statement.setString(7, x);
statement.addBatch();
statement.executeUpdate();
connection.commit();
运行时会产生异常。堆栈跟踪:
java.sql.SQLException: No value specified for parameter 8
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2603)
at com.mysql.jdbc.PreparedStatement.addBatch(PreparedStatement.java:1032)
...
为什么会发生这种情况?“8 参数”应该是什么?代码在普通的 INSERT 语句中运行良好,但是当我添加 ON DUPLICATE KEY UPDATE 时开始失败。
【问题讨论】:
-
您需要为查询中的所有
?(参数)提供参数。 -
题外话:你为什么引用你的列名?
标签: java mysql prepared-statement