標籤:空白 建立 let 檔案格式 result csv檔案 string strong ora
不管是開發還是測試,工作中經常需要去批量新增測試資料,但是大量資料的新增速度有時候讓我們苦不堪言,下面通過兩種方式完成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秒
ORACLE匯入大量資料的兩種方式比較