getGeneratedKeys在executeBatch之后返回空ResultSet

问题描述 投票:-1回答:1

我正在尝试使用PreparedStatement对几个记录进行批量插入。但是,每当我在ResultSet上调用next时,我就会一直变错

public ResultSet insert_into_batch(ArrayList<Movie> values) throws SQLException
{
    conn.setAutoCommit(false);
    ArrayList<String> added = new ArrayList<String>();
    String stmt = "INSERT INTO movies (id,title,year,director) VALUES (?,?,?,?)";
    PreparedStatement psInsertRecord = conn.prepareStatement(stmt, Statement.RETURN_GENERATED_KEYS);
    for (Movie movie : values)
    {
        if (!added.contains(movie.getId())) {
            added.add(movie.getId());
            psInsertRecord.setString(1, movie.getId());
            psInsertRecord.setString(2, movie.getTitle());
            psInsertRecord.setInt(3, movie.getYear());
            psInsertRecord.setString(4, movie.getDirector());
            psInsertRecord.addBatch();
        }
    }
    psInsertRecord.executeBatch();
    conn.commit();
    conn.setAutoCommit(true);
    return psInsertRecord.getGeneratedKeys();
}
java mysql jdbc
1个回答
0
投票

我发现你的代码有三个潜在的问题。

  1. 您插入具有显式ID的记录,因此可能未生成任何密钥。生成的密钥用于数据库系统生成标识符时,但您的代码会显式生成它(某些数据库系统仍将生成结果集,但不是全部,在这种情况下不确定MySQL)。
  2. 批量执行后直接提交连接,因此执行创建的生成的密钥结果集(如果有)将已关闭或相关信息已清除。虽然在那种情况下调用getGeneratedKeys()时我会期望驱动程序抛出异常。
  3. JDBC规范声明它是实现定义的qzexswpoi是否支持批处理执行,因此它可能根本不受支持(但是快速查看MySQL Connector / J的来源表明它受支持)。
© www.soinside.com 2019 - 2024. All rights reserved.