Oracle Java批量导数据

本文介绍了一个使用Java批量向Oracle数据库中插入数据的方法。通过关闭自动提交并使用PreparedStatement的批处理功能,实现从文本文件读取数据并高效地插入到指定的表中。此过程包括连接数据库、设置SQL模板、读取外部文件以及执行批量插入操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



package com.ceair.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

public class Main2 {
	
	public static void main(String[] args) throws SQLException, ClassNotFoundException, FileNotFoundException {
		   String url = "jdbc:oracle:thin:@192.168.1.190:1521:ORCL"; 
		   String user = "sys as sysdba ";
		   String password = "oracle";
		   StringBuffer sql = new StringBuffer();
		   sql.append("insert into laocao values(to_date(? ,'yyyy-mm-dd'),to_date(?,'yyyy-mm-dd'), ?, ?, ? , ?, ?, ?)");
		   Class.forName("oracle.jdbc.driver.OracleDriver");
		   Connection con = (Connection) DriverManager.getConnection(url,user,password);
		   // 关闭事务自动提交
		   con.setAutoCommit(false);
		   Scanner in = new Scanner(new File("C:\\Users\\liyang\\Desktop\\laocao3.txt")) ;
		   int sum = 0 ;
		   while(in.hasNext()){
			    int T = 1000 ;
			    Long startTime = System.currentTimeMillis();
			    PreparedStatement pst = (PreparedStatement) con.prepareStatement(sql.toString());
			    while((T-- > 0) && in.hasNext()){
					String str = in.nextLine() ;
					String[] s = str.split("\t");
					pst.setString(1, s[0]);
					pst.setString(2, s[1]);
					pst.setString(3, s[2]);
					pst.setString(4, s[3]);
					pst.setString(5, s[4]);
					pst.setString(6, s[5]);
					pst.setString(7, s[6]);
					pst.setString(8, s[7]);
					pst.addBatch(); // 把一个SQL命令加入命令列表
				    sum++ ;
			    }
			    pst.executeBatch();
			    con.commit(); // 语句执行完毕,提交本事务
			    pst.close();
			    Long endTime = System.currentTimeMillis();
				System.out.println(sum + "  用时:" + (endTime - startTime) + "ms");
			}
		    con.close();
   }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值