不管是開發還是測試,工作中經常需要去批量新增測試數據,但是大量數據的新增速度有時候讓我們苦不堪言,下面通過兩種方式完成oracle數據的批量新增,比較兩種方式的效率。
第一種方式:采用工具導入sql文件
以10w條數據為例,通過java程序生成insert語句,采用sqlplus進行導入
1、通過簡單的JAVA程序生成sql腳本
public class GenerateSQLFile { public static void main(String[] args) throws Exception { File file = new File("d:" + File.separator + "data.sql"); OutputStream out = new FileOutputStream(file, true); for (int i = 1; i <= 100000; i++) { String str = "insert into t_test(id,name) values(" + i + ",'hello world" + i + "');\r\n"; byte b[] = str.getBytes(); out.write(b); } out.close(); } }
執行程序,生成的sql腳本如下所示:
insert into t_test_1(id,name) values(1,'hello world1');
insert into t_test_1(id,name) values(2,'hello world2');
insert into t_test_1(id,name) values(3,'hello world3');
... ...
2、新建表,導入數據
以scott/tiger登錄sqlplus;
新建t_test表:create tablet_test_1(id int,name varchar2(255));
創建表成功后執行:@D:\data.sql,逐行插入數據
3、測試結果
以sqlplus執行sql腳本導入10W條數據的時間大約是5分鍾
第二種方式:采用sql loader工具
sql loader可以將文本格式存放的數據導入到oracle,是一個進行數據遷移的非常方便而且通用的工具。
下面通過java程序生成csv文件,以100萬條測試數據為例,通過sql loader進行數據導入
期望生成的csv數據文件格式如下:
1,hello1
2,hello2
3,hello3
... ...
1、生成數據文件
100萬條數據的csv文件同樣由java程序生成:
File file = new File("d:" + File.separator + "data.csv"); // 要操作的文件 OutputStream out = null; // 聲明字節輸出流 out = new FileOutputStream(file, true); for (int i = 1; i <= 100000; i++) { String str = i+","+"hello"+i+"\r\n"; byte b[] = str.getBytes(); out.write(b); } out.close();
2、創建表格t_test_2
create table t_test_2(id varchar2(255),name varchar2(255));
3、建立控制文件test.ctl,腳本如下
load data
infile data.csv
into table t_test_2
(
id char terminated by ',',
name char terminated by whitespace
)
參數說明:
Infile data.csv: 指定數據源文件 這里我們省略了默認的 discardfile result.dsc badfile result.bad
into table t_test_2:默認是INSERT,也可以into table resultxt APPEND為追加方式,或REPLACE
terminated by ',':指用逗號進行字段的分隔
terminated by whitespace: 表示結尾以空白分隔
其它參數參考可使用命令:d:\>sqlldr
4、導入數據:
將test.ctl文件和data.csv文件放置在D盤根目錄下,在命令行中運行:
D:\>sqlldr userid=scott/tiger control=test.ctl
5、測試結果:通過sql loader進行數據導入,10萬條數據毫秒級導入,100萬條數據耗時10秒