我正在尝试使用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();
}
我发现你的代码有三个潜在的问题。
getGeneratedKeys()
时我会期望驱动程序抛出异常。