Python-工具-批量插入INSERT语句(将sql文件导入数据库)


    实际工作中,对于数据导入导出可以使用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()

 最近在使用中发现,如果出现与编码格式不符的字符则直接抛出,有解决方案的记得留言啊。


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM