実行するSQLコマンドの挿入または更新が多数ある場合は、java.sql.Statement addBatch(String sqlCmd)を使用できます。 それらをグループ化してから、java.sql.Statement executeBatch()を実行するメソッド すべてのコマンドをデータベースサーバーに一度にコミットします。
JDBCバッチ操作に関する注意事項
- sqlコマンドがグループごとにデータベースサーバーに送信されるため、データベース通信のパフォーマンスが向上します。これにより、クライアントとサーバー間の通信コストを削減できます。
- バッチ操作はターゲットデータベースサーバーの機能であり、jdbcドライバーでは必要ありません。
Connection.getMetaData().supportsBatchUpdates()を使用できます 宛先データベースがバッチ更新をサポートしているかどうかを確認します。 - バッチ操作は、コマンドの挿入だけでなく、コマンドの更新と削除にも使用できます。
-
java.sql.Connection.setAutoCommit(false)を使用する必要があります バッチデータベースアクションを実行する前にデータベースの自動コミットを無効にします。 - バッチ操作を実行した後、
java.sql.Connection.commit()を使用します 一度にデータベースサーバーに操作をコミットします。 -
java.sql.Connection.setAutoCommit(true)を実行する必要があります 後のdb操作で自動コミットを有効にします。 - バッチSQLは複数のテーブルを操作できます。
バッチ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);
完全なサンプルコード
以下の例では、mysqlデータベースを使用して、データをテーブルの教師と生徒にバッチで挿入および更新します。 JDBC MySQLの詳細については、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);
}
ソースコード:
- [download id =” 2551”]