
net.dongliu.dbutils.BatchInsertSQLContext Maven / Gradle / Ivy
package net.dongliu.dbutils;
import net.dongliu.commons.io.Closeables;
import net.dongliu.dbutils.exception.UncheckedSQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* For query sql execute
*
* @author Liu Dong
*/
public class BatchInsertSQLContext extends BatchSQLContext {
@Override
protected BatchInsertSQLContext self() {
return this;
}
/**
* Execute a batch of INSERT operations, and return keys.
*
* @return The key column result set of inserted row. will try retrieve auto generated columns
*/
public SQLResultSet execute() {
try {
PreparedStatement statement = keyColumns == null ?
connection.prepareStatement(clause, Statement.RETURN_GENERATED_KEYS)
: connection.prepareStatement(clause, keyColumns);
try {
for (Object[] param : params()) {
this.fillStatement(statement, param);
statement.addBatch();
}
statement.executeBatch();
ResultSet rs = statement.getGeneratedKeys();
if (closeConn) {
return new SQLResultSet(rs, statement, connection);
} else {
return new SQLResultSet(rs, statement);
}
} catch (Throwable e) {
Closeables.closeQuietly(statement);
throw e;
}
} catch (SQLException e) {
if (closeConn) {
Closeables.closeQuietly(connection);
}
throw new UncheckedSQLException(e);
} catch (Throwable t) {
if (closeConn) {
Closeables.closeQuietly(connection);
}
throw t;
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy