最近遇到乙個比較蛋疼的事,需要把70g的csv資料匯入到oracle資料庫中。一開始覺得沒啥,可是當開始匯入的時候我發現乙個問題,好tm慢…
最後問了好多朋友,找了個批量匯入的方法
下面是我的資料格式:
第一列是時間格式的資料,oracle資料庫插入資料對時間格式的資料要求和其他資料庫不同,需要進行格式轉換,所以插入語句的建立要寫對,具體可以自己去了解一下
oracle_prepare.py檔案,這個是用來資料庫互動的:
import cx_oracle
class
oreclecommand
(object):
def__init__
(self)
: self.host =
"localhost:1521/orcl"
# ip/埠
self.user =
"****"
# 使用者名稱
self.password =
"****"
# 密碼
defconnectoracle
(self)
:try
: self.conn = cx_oracle.connect(self.user, self.password, self.host)
self.cursor = self.conn.cursor(
)except cx_oracle.error as error:
print
(error)
definsertdatatimeseries
(self, my_dict)
:try
: self.cursor.prepare(
"insert into 表名(datetimes,record,ux,uy,uz,ts,diag_sonic,co2,h2o,diag_irga,tc,amb_tmpr,amb_press,co2_sig_strgth,h2o_sig_strgth) values (to_timestamp(:1,'yyyy-mm-dd hh24:mi:ss.ff6'),:2,:3,:4,:5,:6,:7,:8,:9,:10,:11,:12,:13,:14,:15)"
) self.cursor.executemany(
none
, my_dict)
self.conn.commit(
)except cx_oracle.error as error:
print
(error)
defcloseoracle
(self)
: self.cursor.close(
) self.conn.close(
)
csv_to_oracle.py檔案,操作csv檔案
import os
import csv
from oracle_prepare import oreclecommand
defcsv_with
(csv_path, file_name_list)
: result =
oreclecommand = oreclecommand(
) oreclecommand.connectoracle(
)#建立資料庫連線
for file_item_name in file_name_list:
#遍歷檔名
csv_all_path = os.path.join(csv_path, file_item_name)
#建立單個檔案全路徑
with
open
(csv_all_path,
"r")
as csv_file:
reader=csv.reader(csv_file)
for line_list in reader:
(line_list[0]
,line_list[1]
,line_list[2]
,line_list[3]
,line_list[4]
,line_list[5]
,line_list[6]
,line_list[7]
,line_list[8]
,line_list[9]
,line_list[10]
,line_list[11]
,line_list[12]
,line_list[13]
,line_list[14]
))oreclecommand.insertdatatimeseries(result)
#插入資料入庫
result.clear(
)#一定要清空列表!!!,不然資料會累積
oreclecommand.closeoracle(
)#關閉資料庫連線
csv_path =r"e:\time_csv"
#所有csv的檔案路徑
file_name_list = os.listdir(csv_path)
#獲取所有檔案路徑下的檔名
csv_with(csv_path, file_name_list)
推薦參考
批量插入oracle資料庫
odp技術,引數可以為陣列 注意事項 1 時間處理 防止資料庫中有date型別的資料,不設定格式則會出現無效月份的情況,如 new oracledate 2011 08 26 17 18 19 oracleglobalization og oracleglobalization.getclienti...
Mybatis批量插入Oracle資料庫
首先要說明的是,mybatis批量插入oracle和mysql是不同的,鄙人親身經歷,使用mysql的批量插入會報各種錯,在查了很多資料,最終使用pl sql來批量插入sql語句為 insert into employee id,name,age,nameen select 1 張三 31 zhan...
DataTable批量插入資料庫
最近在將excel中的檔案匯入到資料庫中,用程式進行編寫,由於資料量較大所以速度很慢,後來採用了sqlbulkcopy類,解決了速度的問題,我就insert語句,sqldataadapter.update dataset,tablename sqlbulkcopy.writetoserver dat...