向数据库添加100W 条数据 性能测试 ;
参考的相关网站目录:
JDBC实现往MySQL插入百万级数据
MySql 的批量操作,要加rewriteBatchedStatements参数
JDBC事务控制管理
测试代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.UUID;
public class Test {
private String url = "jdbc:oracle:thin:@XXXXXX:1521:XXXX";
private String user = "XXXX";
private String password = "XXXX";
public void Test(){
Connection conn = null;
PreparedStatement pstm =null;
ResultSet rt = null;
UUID uuid = UUID.randomUUID();
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
String sql = "INSERT INTO XXXXX(XX,XX,XXX) VALUES(?,?,?)";
pstm = conn.prepareStatement(sql);
conn.setAutoCommit(false);
Date start_time = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
String s_start_time = df.format(start_time);
System.out.println("
************************start_time : " + s_start_time + "************************");// new Date()为获取当前系统时间
Random rand = new Random();
int a,b,c,d;
for (int i = 1; i <= 1000000; i++) {
pstm.setInt(1, i);
pstm.setInt(2, i);
/* a = rand.nextInt(10);
b = rand.nextInt(10);
c = rand.nextInt(10);
d = rand.nextInt(10);*/
pstm.setString(3, uuid+"11111111111111111111111111111111111111111111111111"
+"11111111111111111111111111111111111111111111111111111111111111111111"
);
pstm.addBatch();
}
pstm.executeBatch();
conn.commit();
Date end_time = new Date();
String s_end_time = df.format(end_time);
// 时间差
long time_diff = end_time.getTime() - start_time.getTime();
System.out.println("Succeed!" +
" It Takes times : " + time_diff +
" ms ;
*************************end_time : " + s_end_time + "*************************");//record
/*Long endTime = System.currentTimeMillis();*/
/* System.out.println("OK,用时:" + (endTime - startTime)); */
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}finally{
if(pstm!=null){
try {
pstm.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
}
public static void main(String[] args) {
Test test = new Test();
test.Test();
}
}