专业编程教程与实战项目分享平台

网站首页 > 技术文章 正文

使用python如何将查询结果,转换为insert脚本?

ins518 2024-11-16 21:09:29 技术文章 7 ℃ 0 评论
import cx_Oracle as ora
import time
import re
from queue import Queue
import os
'''
适用一段sql内,只有一个from的,有嵌套的,需要调整;
需要写入:file_path,获取sql文件路径,注意最后的sql不能有分号;
输出文件:08_out,需要提前清空文件夹内的文件;
写slq最好加上scharma名称;
'''
# 清空路径下的文件
out_path="./08_out"
l=os.listdir(out_path)
for i in l:
    rm_path=out_path+'/'+i
    os.remove(rm_path)
# 获取sql
file_path=r"C:\Users\admin\Desktop\t\t1.sql"
with open(file_path,'r',encoding='utf-8') as f:
    t=f.read()
    l=t.split(';')
# values字符串拼接:传入一个元组,返回字符串,对记录进行处理
# t=('f','e',None)
def get_value(t):
    L=[]
    for i in t:
        if i==None:
            L.append('NULL')
        else:
            L.append(i)
    tup=str(tuple(L))
    s = '''VALUES%s''' %tup
    new_s = s.replace("'NULL'", 'NULL')
    return new_s
# 传入列表,返回一个字符串,用于处理字段名称
def get_ziduan(l):
    tup = str(tuple(l))
    s = '''%s''' % tup
    return s.replace("'","")
# 取出表名称
def get_table(s):
    uppe_s=s.upper()
    if 'WHERE' in uppe_s:
        resp=''.join(re.findall('(?<=FROM).*(?=WHERE)',uppe_s,re.S))
    else:
        resp=''.join(re.findall('(?<=FROM).*',uppe_s,re.S))
    resp1=resp.strip()
    if '.' in resp1:
        resp2=resp1.replace(''.join(re.findall('.*\.', resp1, re.S)), '')
    else:
        resp2=resp1
    return resp2

path=r"D:\33.oracle\instantclient-basic-windows.x64-21.11.0.0.0dbru\instantclient_21_11" # oracle数据库客户端存放路径
ora.init_oracle_client(path)

conn = ora.connect('用户名/密码@ip地址/数据库名字')#这里的顺序是用户名/密码@oracleserver的ip地址/数据库名字
cursor = conn.cursor()
print('连接数据库成功!')
# 循环取出每一段sql语句
for i in l:
    sql = i
    all = cursor.execute(sql)
    all_data=all.fetchall()
    # 获取字段名称列表
    columns = [row[0] for row in cursor.description]
    q=Queue()
    # 循环取出每行记录
    for n in all_data:
        out_sql='INSERT INTO '+get_table(i)+get_ziduan(columns) +'\n'+ get_value(n)+';'+'\n\n'
        q.put(out_sql)
        # 把所有的查询结果放在一个文件内
        with open('./08_out/resp.sql', 'a', encoding='utf-8') as f:
            f.write(out_sql)
    print('完成表:%s'%get_table(i))
    #根据不同的表名,写出不同的文件内
    while not q.empty():
        with open('./08_out/%s.sql'%get_table(i), 'a', encoding='utf-8') as f:
            f.write(q.get())
    time.sleep(2)






Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表