實際工作中,對於數據導入導出可以使用PLSQL Developer/Tools/Import Tbales功能實現,但由於回滾段的限制對於導入的數據量存在限制。
可以通過修改文件中的語句,控制部分提交,但數據量大文件也大,打開文件設置提交也是件麻煩事。
所以編寫一個Python腳本,讀取文件中語句並進行部分提交,以Oracle數據庫為基礎。
導入文件需是工具導出的標准格式且導入文件需和腳本同一路徑。
import cx_Oracle import datetime db = cx_Oracle.connect('用戶名/密碼@服務名') dblj = db.cursor() count = 0 ycts = 0 cgts = 0 str1 ='' start = datetime.datetime.now().strftime('%Y_%m_%d_%H:%M:%S.%f') while(1 == 1): file_name = input("請輸入文件名\n") #print(2) fn = file_name[-3:].upper() if(fn != 'SQL'): print("文件名無效,必須是sql文件\n") continue fileobject = open(file_name) for line in fileobject: st = line[0:6].upper() #print(line[0:6].upper()) if(st =='INSERT'): try: str1 = str1.replace(';','') dblj.execute(str1) db.commit() count = count + 1 cgts = cgts + 1 if(count == 500): count = 0 print("500") except cx_Oracle.DatabaseError: ycts = ycts + 1 pass str1 = line else: str1 = str1 + line str1 = str1.split(';') str1 = str1[0] dblj.execute(str1) db.commit() cgts = cgts + 1 ycts = ycts - 1 end = datetime.datetime.now().strftime('%Y_%m_%d_%H:%M:%S.%f') print("成功"+str(cgts)+"條","失敗"+str(ycts)+"條") print(start) print(end) fileobject.close() dblj.close()
最近在使用中發現,如果出現與編碼格式不符的字符則直接拋出,有解決方案的記得留言啊。
