前些天有个需要。要处理一个有20000行3MB大小的txt文件。要把每一行插入到数据库里,而且是web系统下,
我按一般preparedStatement写完了,一测试,妈妈呀,跑了近20分钟,这还了得,
感激想办法,请教高手,改用JDBC的批处理。简单列下代码
File file = new File("D:\\test.txt");
Connection conn = ConnectionManager.getConnection();
String sql = "insert into table(param1,param2,param3,param4,param5,param6,param7,param8,param9,param10) values(?,?,?,?,?,?,?,?,?,?)";
PreparedStatement psmt = null;
try {
conn.setAutoCommit(false);
psmt = conn.prepareStatement(sql);
if(file.exists() && file.isFile()){
try {
FileReader fr = new FileReader(file);
BufferedReader reader = new BufferedReader(fr);
String line = reader.readLine();
int count = 1;
while(line!=null){
...........
psmt.setXXX();//set参数
...........
psmt.addBatch(); //加入批处理
if(count % 5000 == 0){
//设置5000为一个批处理
psmt.executeBatch();
conn.commit();
psmt.clearBatch();
}
count++;
line = reader.readLine();
}
psmt.executeBatch();
conn.commit();
psmt.clearBatch();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (SQLException e1) {
e1.printStackTrace();
}finally{
ConnectionManager.free(conn, psmt);
}
完了我一测试,真快啊,2秒搞定。哈哈,写下来以后用。