在进行大批量数据插入、更新时 使用hibernate明显做了很多无用功,导致反应时间过长;在这种情况下可以使用JDBC批处理完成数据库操作。
package com.jdbc.batch;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
/**
* Created by IntelliJ IDEA.
* User: DiaoLei
* Date: 2010-6-3
* Time: 21:51:48
* To change this template use File | Settings | File Templates.
*/
public class Batch {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//connect DB
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url = "jdbc:oracle:thin:@localhost:1521:ora10g"; //ora10g为数据库的SID
String username = "res_col";
String password = "res_col";
conn = DriverManager.getConnection(url, username, password);
String sql = "Insert INTO testjdbc(num,ask_num) VALUES(?,?)";
// String sql = "update testjdbc set ask_num = ? where num = ?"; //更新的时候使用下边注释的两行
ps = conn.prepareStatement(sql);
//测试
int k[] = {1, 2, 3, 4, 5};
String str[] = {"0.99", "0.98", "0.97", "0.96", "0.95"};
for (int i = 0; i < 5; i++) {
ps.setString(1, "" + k[i] + ""); //代表上边sql语句的第一个?的value
ps.setString(2, str[i]); //代表上边sql语句的第二个?的value
/* ps.setString(2, "" + k[i] + "");
ps.setString(1, str[i]);*/
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (ClassNotFoundException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (InstantiationException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}