從一個表中查詢數據並且修改後插入另一個表,利用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()