任意のテーブルにレコードを追加する
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
// データベースへの接続を確立
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// トランザクションの開始
connection.setAutoCommit(false);
// 動的なカラム名のリストを作成
List<String> dynamicColumnNames = new ArrayList<>();
dynamicColumnNames.add("column1");
dynamicColumnNames.add("column2");
dynamicColumnNames.add("column3");
// ... 他のカラム名を追加
// 動的なINSERT文のテンプレートを生成
StringBuilder insertSQL = new StringBuilder("INSERT INTO mytable (");
for (String columnName : dynamicColumnNames) {
insertSQL.append(columnName).append(", ");
}
// カラム名のリストから余分なカンマを削除
insertSQL.setLength(insertSQL.length() - 2);
insertSQL.append(") VALUES (");
for (int i = 0; i < dynamicColumnNames.size(); i++) {
insertSQL.append("?, ");
}
// パラメータ用のプレースホルダーを追加
insertSQL.setLength(insertSQL.length() - 2);
insertSQL.append(")");
preparedStatement = connection.prepareStatement(insertSQL.toString());
// ダミーのデータを挿入するループ
for (int i = 0; i < 100000; i++) {
// 各カラムの値を設定
for (int j = 0; j < dynamicColumnNames.size(); j++) {
preparedStatement.setString(j + 1, "value" + i); // パラメータインデックスは1から始まるため、j + 1
}
// バッチに追加
preparedStatement.addBatch();
// バッチサイズが一定数に達したら実行
if (i % 1000 == 0) {
preparedStatement.executeBatch();
}
}
// 残りのバッチを実行
preparedStatement.executeBatch();
// トランザクションのコミット
connection.commit();
} catch (SQLException e) {
e.printStackTrace();
// エラーが発生した場合、トランザクションをロールバック
try {
if (connection != null) {
connection.rollback();
}
} catch (SQLException rollbackException) {
rollbackException.printStackTrace();
}
} finally {
try {
if (preparedStatement != null) {
preparedStatement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException closeException) {
closeException.printStackTrace();
}
}
}
}