將excel表里面的數(shù)據(jù)(str居多)進行邏輯運算后存入MySQL數(shù)據(jù)庫
標題就是需求,使用語言是python,用到了pymysql庫和pandas庫(沒有的話自行pip install),代碼如下:
import pymysql
import pandas as pd
# 連數(shù)據(jù)庫
conn = pymysql.connect(host='localhost', user='root', password='0000', db='p1')
# 創(chuàng)建列表
excel_file = pd.ExcelFile('數(shù)組.xlsx')
df1 = pd.read_excel(excel_file, sheet_name='Sheet1')
df2 = pd.read_excel(excel_file, sheet_name='Sheet2')
# 將df1和df2轉(zhuǎn)換為列表
list1 = df1.values.tolist()
list2 = df2.values.tolist()
# 進行數(shù)據(jù)對比并更新列表
i = 0
j = 0
while i < len(list1):
? ? print('第' + str(i) + f'行,進度{round(i / 24956 * 100, 1)}%')
? ? while j < len(list2):
? ? ? ? if str(list1[i][0]) == str(list2[j][0]) and str(list1[i][1]) == str(list2[j][1]) and (str(list1[i][5]) == str(list2[j][3]) or str(list1[i][6]) == str(list2[j][5])) and str(list1[i][8]) == str(list2[j][9]):
? ? ? ? ? ? list1[i][13] = list2[j][15]
? ? ? ? ? ? list1[i][14] = list2[j][16]
? ? ? ? ? ? list1[i][15] = list2[j][17]
? ? ? ? ? ? list1[i][16] = list2[j][18]
? ? ? ? ? ? list1[i][17] = list2[j][19]
? ? ? ? ? ? list1[i][18] = list2[j][20]
? ? ? ? j += 1
? ? j = 0
? ? i += 1
# 創(chuàng)建列表的idx用來給sql提供idx
idxs = []
columns_sql = ""
for idx in df1.columns:
? ? idxs.append(str(idx))
? ? print(idx)
? ? columns_sql += f"{str(idx)} VARCHAR(255) NOT NULL, "
print(len(idxs))
# 創(chuàng)建一個游標對象
cursor = conn.cursor()
# 定義創(chuàng)建表的SQL語句
sql = f'''CREATE TABLE StudyTable (
? ? ? ? ? ? {columns_sql[:-2]},
? ? ? ? ? ? PRIMARY KEY ({idxs[0]})
? ? ? ? ? ? )'''
# 生成數(shù)據(jù)表
cursor.execute(sql)
# 將二維列表插入到MySQL表中
placeholders = ', '.join(['%s'] * len(idxs))
insert_sql = f"INSERT INTO StudyTable VALUES ({placeholders})"
# 執(zhí)行SQL語句
cursor.executemany(insert_sql, list1)
# 提交事務
conn.commit()
# 關閉連接
cursor.close()
conn.close()