----------------------------------------------------oracle高效批量插入方法----------------------------------------------------------------------------------
//简单实用的oracle数据插入方法
public class ReadTextToOracle{
//oracle数据库连接参数
private static String url="jdbc:oracle:thin:@xxx.xx.xx.xx:1521:m8cq"; //xxx.xx.xx.xx即数据库所在服务器ip 本地可用localhost
//用户名
private static String user="user";
//密码
private static String password="password";
public static void main(String[] args) throws IOException, Exception {
int i = 1;
String fileText = null;
Connection conn = null;
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, password);
//关闭自动提交
conn.setAutoCommit(false);
//itcheng表中字段为 name age data1 data2 data 3
PreparedStatement pst = conn.prepareStatement("insert into itcheng values(?,?,?,?,?)"); //预编译
//获得文件输入流
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File("F:/fileTest/itcheng.txt")), "utf-8");
BufferedReader read = new BufferedReader(isr);
long start = System.currentTimeMillis();
while ((fileText = read.readLine()) != null) {
//此处案例文本数据格式为str1|str2|str3|str4|str5 所以自己按需求修改 这里仅展示简单易懂类型
String[] readdate = fileText.split("\\|");//此处需要注意转义
// 当数据满100条批量插入
if (i % 100 == 0) {
// 语句执行完毕,提交本事务
pst.executeBatch();
// 此处的事务回滚是必须的,网上很多代码没有处理,会导致插入数据不完整。
try {
conn.commit();
} catch (Exception e) {
conn.rollback();
}
} else {
pst.setString(1, readdate[0]);
pst.setString(2, readdate[1]);
pst.setString(3, readdate[2]);
pst.setString(4, readdate[3]);
pst.setString(5, readdate[4]);
pst.addBatch();
}
i++;
}
// 考虑到最后不足100的数据,语句执行完,提交事务
pst.executeBatch();
try {
conn.commit();
} catch (Exception e) {
conn.rollback();
}
long end = System.currentTimeMillis();
// 此处是打印插入效果
System.out.println("此次插入" + i + "条,共耗时" + (end - start));
read.close();
}
}