Java + MySQL - 添加“重复密钥更新”

时间:2013-08-14 14:19:52

标签: java mysql prepared-statement

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

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

运行此操作时,会生成异常。 Stacktrace:

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

2 个答案:

答案 0 :(得分:4)

  

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

答案 1 :(得分: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);

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