Quando hai molti comandi di inserimento o aggiornamento da eseguire, puoi usare java.sql.Statement addBatch(String sqlCmd) metodo per raggrupparli e quindi eseguire java.sql.Statement executeBatch() per eseguire il commit di tutti i comandi al server del database contemporaneamente.
Note sull' operazione in batch JDBC
- Migliora le prestazioni di comunicazione del database perché i comandi sql sono stati inviati al server del database per gruppo, questo può ridurre il costo della comunicazione tra client e server.
- L'operazione batch è una funzionalità del server di database di destinazione, non è richiesta dal driver jdbc. Puoi utilizzare
Connection.getMetaData().supportsBatchUpdates()per verificare se il database di destinazione supporta o meno l'aggiornamento batch. - L'operazione batch può essere utilizzata non solo per inserire comandi, ma anche per aggiornare ed eliminare comandi.
- Dovresti usare
java.sql.Connection.setAutoCommit(false)per disabilitare il commit automatico del database prima di eseguire azioni batch db. - Dopo aver eseguito le operazioni batch, utilizza
java.sql.Connection.commit()per eseguire immediatamente le operazioni sul server del database. - Dovresti eseguire
java.sql.Connection.setAutoCommit(true)per abilitare il commit automatico per le successive operazioni db. - Sql in batch può gestire più tabelle.
Insieme di frammenti di codice SQL
/* Get connection object. */
Connection dbConn = this.getMySqlConnection(ip, port, dbName, userName, password);
/* Disable auto commit. */
dbConn.setAutoCommit(false);
/* Get statement object. */
Statement stmt = dbConn.createStatement();
/* Add sql in batch, each sql can operate different table. */
stmt.addBatch(sql1);
stmt.addBatch(sql2);
stmt.addBatch(sql3);
stmt.addBatch(sql4);
stmt.addBatch(sql5);
stmt.addBatch(sql6);
/* Execute batch sql to db server. */
int updateCountArr[] = stmt.executeBatch();
/* Do not forget commit. */
dbConn.commit();
/* Enable auto commit for later db operation. */
dbConn.setAutoCommit(true);
Codici di esempio completi
L'esempio seguente utilizzerà il database mysql, inserirà e aggiornerà i dati nella tabella insegnante e studente in batch. Puoi fare riferimento a Come utilizzare JDBC per connettere il database MySql per saperne di più su JDBC MySQL.

public void testBatchUpdate(String ip, int port, String dbName, String userName, String password)
{
String sqlArr[] = new String[6];
sqlArr[0] = "insert into student values('richard','example@sqldat.com')";
sqlArr[1] = "insert into student values('jerry','example@sqldat.com')";
sqlArr[2] = "insert into teacher(name, email) values('tom','example@sqldat.com')";
sqlArr[3] = "update teacher set email = 'example@sqldat.com' where name = 'hello'";
sqlArr[4] = "insert into teacher(name, email) values('song','example@sqldat.com')";
sqlArr[5] = "insert into teacher(name, email) values('jerry','example@sqldat.com')";
this.executeBatchSql(ip, port, dbName, userName, password, sqlArr);
}
/* Batch execute insert, update, delete commands. */
public void executeBatchSql(String ip, int port, String dbName, String userName, String password, String sqlArr[])
{
/* Declare the connection and statement object. */
Connection dbConn = null;
Statement stmt = null;
try
{
/* Get connection object. */
dbConn = this.getMySqlConnection(ip, port, dbName, userName, password);
/* Check whether this db support batch update or not. */
boolean supportBatch = dbConn.getMetaData().supportsBatchUpdates();
if(supportBatch)
{
System.out.println("This database support batch update.");
}else
{
System.out.println("This database do not support batch update.");
}
/* Disable auto commit. */
dbConn.setAutoCommit(false);
/* Get statement object. */
stmt = dbConn.createStatement();
if(sqlArr!=null)
{
int len = sqlArr.length;
for(int i=0;i<len;i++) { String sql = sqlArr[i]; stmt.addBatch(sql); System.out.println("Batch add sql : " + sql); } if(len > 0)
{
/* The return array save each command updated rows number. */
int updateCountArr[] = stmt.executeBatch();
dbConn.commit();
dbConn.setAutoCommit(true);
System.out.println("Execute batch sql successfully. ");
int updateLength = updateCountArr.length;
for(int j=0 ; j < updateLength; j++)
{
int updateCount = updateCountArr[j];
System.out.println("updateCount : " + updateCount);
}
}
}
}catch(Exception ex)
{
ex.printStackTrace();
}finally
{
this.closeDBResource(stmt, dbConn);
}
}
public static void main(String[] args) {
/* Below are db connection required data. */
String ip = "localhost";
int port = 3306;
String dbName = "test";
String userName = "root";
String password = "";
/* Create an instance. */
JDBCStatementExample jdbcStatementExample = new JDBCStatementExample();
jdbcStatementExample.testBatchUpdate(ip, port, dbName, userName, password);
}
Codice sorgente:
- [ID download=”2551″]