0

我有以下查询用于准备好的语句:

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时开始失败。

4

2 回答 2

5

什么是“8参数”

您添加到查询中的第 8 个参数:

...VALUES(?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE `col1`=?
          1  2  3  4  5  6  7...                      here it is - 8th!

无论如何,您实际上根本不需要重复值的参数:

INSERT INTO mytable VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE `col1`=values(col1), `col2`=values(col2), 
`col3`=values(col3), `col4`=values(col4), `col5`=values(col5),
`col6`=values(col6), `col7`=values(col7);
于 2013-08-14T14:34:06.430 回答
1

您总共有 14 个?标记,即参数。但是,在创建PreparedStatement对象时,您只设置了 7。

您需要具有setter与.?PreparedStatement

你需要做 -

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);

// the following should have the values you want to update when there a duplicate key
statement.setInt(8, x);
statement.setDouble(9, x);
statement.setLong(10, x);
statement.setLong(11, x);
statement.setDouble(12, x);
statement.setString(13, x);
statement.setString(14, x);

一个建议 - 您不需要引用列名。

于 2013-08-14T14:23:00.857 回答