c 3 p 0のデータベース接続プールのマルチスレッドテスト
2674 ワード
// c3p0
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Iterator;
import java.util.Random;
import com.cn.wangk.db.DbUtil;
import com.cn.wangk.db.MyDbutil;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class DbThread extends Thread {
private int ThreadNum = 0;
private ComboPooledDataSource ds;
public DbThread(int num,ComboPooledDataSource ds) {
ThreadNum = num;
this.ds = ds;
}
public void run() {
Random random = new Random();
System.out.println(" "+ThreadNum+" ");
int count = 0;
Connection connection = null;
try {
connection = ds.getConnection();
} catch (SQLException e2) {
e2.printStackTrace();
}
try {
connection.setAutoCommit(false);
while(count<30){
try {
int inum = random.nextInt(1000);
Thread.sleep(inum);
} catch (InterruptedException e) {
e.printStackTrace();
}
Statement stmt = connection.createStatement();
System.out.println(" "+ThreadNum+", “"+count+"” ");
stmt.execute("insert into test1 (name,cb)values(' "+ThreadNum+", “"+count+"” !','"+ThreadNum+"')");
stmt.close();
count++;
}
if(ThreadNum==150)
connection.commit();
else
connection.rollback();
connection.setAutoCommit(true);
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
System.out.print(e1.getMessage());
}
System.out.print(e.getMessage());
}finally{
try {
if(connection !=null)
connection.close();
} catch (SQLException e) {
System.out.print(e.getMessage());
}
}
//System.out.println(ThreadNum);
}
/**
* @param args
*/
public static void main(String[] args) {
ComboPooledDataSource ds = new ComboPooledDataSource();
//truncate table test1
// TODO Auto-generated method stub
MyDbutil dbutil = MyDbutil.Open();
//
try {
dbutil.execute("truncate table test1");
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < 500; i++) {
DbThread dbThread = new DbThread(i,ds);
dbThread.start();
}
}
}