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

1 回答 1

0

我发现您的代码存在三个潜在问题。

  1. 您插入具有显式 id 的记录,因此可能没有生成任何键。生成的密钥用于数据库系统生成标识符时,但您的代码显式生成它(一些数据库系统仍然会生成结果集,但不是全部,在这种情况下不确定 MySQL)。

  2. 您在批处理执行后直接提交连接,因此执行创建的生成的密钥结果集(如果有)将已经关闭或相关信息已清除。尽管我希望驱动程序getGeneratedKeys()在这种情况下调用时会引发异常。

  3. JDBC 规范声明是否getGeneratedKeys支持批处理执行是实现定义的,因此它可能根本不受支持(但快速查看 MySQL Connector/J 的源代码表明它是受支持的)。

于 2018-05-19T08:14:14.467 回答