「Java入門」マルチスレッドで100万件テストデータをMySQLにInsertするサンプル

1.TestThreadの定義
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;

public class TestThread extends Thread{
public void run() {
String url = “jdbc:mysql://192.168.85.1/employee";
String name = “com.mysql.jdbc.Driver";
String user = “root";
String password = “123456";
Connection conn = null;
try {
Class.forName(name);
conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false);//自動コミットを停止
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
// 開始時間
Long begin = new Date().getTime();

String prefix = “INSERT INTO employeetbl (t_name,t_password,sex,description,pic_url,school_name,remark) VALUES “;
try {
StringBuffer suffix = new StringBuffer();
conn.setAutoCommit(false);
PreparedStatement pst = (PreparedStatement) conn.prepareStatement(“");
//
for (int i = 1; i <= 10; i++) {
suffix = new StringBuffer();
for (int j = 1; j <= 100000; j++) {

suffix.append(“('" +i*j+"',’123456′"+ “,’男'"+",’システムエンジニア'"+",’www.sample.net'"+",’xx大学'"+",'"+"',’メモ'" +"),");
}
String strSql = prefix + suffix.substring(0, suffix.length() – 1);
pst.addBatch(strSql);
pst.executeBatch();
// トランザクションをコミット
conn.commit();
// 前回のデータをクリア
suffix = new StringBuffer();
}
pst.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
// 終了時間
Long end = new Date().getTime();
// 時間計算
System.out.println(“100万件データの挿入操作が必要な時間 : " + (end – begin) / 1000 + " s");
}
}

2.Mainメソッド
public class DataInsertTest {
public static void main(String[] args) {
for (int i = 1; i <=10; i++) {
new TestThread().start();
}
}
}

Java

Posted by arkgame