编写python脚本,生成迁移数据SQL

从一个表中查询数据并且修改后插入另一个表,利用python脚本读取CSV或者Execl文件。

#!/usr/bin/env python
# _*_ conding:utf-8 _*_
import sys
import os
# import xlrd
import pandas as pd

# id映射的execl表 第一列是原始id 第二列新导入id
fileName = "test.csv"
# 生成sql文件的名字
temp = "temp"
# sql的模板
sql = '''
       INSERT IGNORE INTO    
	   devops_app_service_version(
       helm_config_id,
       harbor_config_id,
			 version,
			 app_service_id,
			 value_id,
			 readme_value_id,
			 image,
			 commit,
			 repository,
			 object_version_number,
			 created_by,
			 creation_date,
			 last_updated_by,
			 last_update_date)
			 SELECT
			   helm_config_id,
			   harbor_config_id,
			   version,
			   {},
			   value_id,
			   readme_value_id,
			   image,
			   commit,
			   repository,
			   object_version_number,
			   created_by,
			   creation_date,
			   last_updated_by,
			   last_update_date
			 FROM devops_app_service_version
			 WHERE app_service_id= {}
		 '''


# 1.打开一个Excel
# def open_excel(file=fileName):
#     data = xlrd.open_workbook(file)
#     return data


# 2.读取Excel生成sql
# 根据索引获取Excel表格中的数据   参数:file:Excel文件路径     colnameindex:表头列名所在行的所以  ,by_index:表的索引
def excel_table_byindex(file=fileName, colnameindex=0, by_index=0):
    fp = open(temp, "a")
    data = pd.read_csv(fileName)
    for index, row in data.iterrows():
        fp.write(sql.format(int(row[1]), int(row[0])))

    # table = data.sheets()[by_index]
    # nrows = table.nrows  # 行数
    # ncols = table.ncols  # 列数
    # for rownum in range(0, nrows):
    #     # 获取一行数据
    #     row = table.row_values(rownum)
    #     logging.info("create transfer sql")
    #     fp.write(sql.format(int(row[1]), int(row[0])))
    fp.close()


# 3.创建一个文件
def create__file(file_name):
    # 判断文件是否存在,不存在则创建
    if not os.path.exists(file_name):
        open(file_name, "w")


def main():
    # create__file(temp)
    excel_table_byindex()


if __name__ == "__main__":
    main()
发布了217 篇原创文章 · 获赞 70 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/weixin_37650458/article/details/103833079