1、準(zhǔn)備好Excel表:
2、數(shù)據(jù)庫建表case2
?字段信息與表格對應(yīng)建表:
文章來源:http://www.zghlxwxcb.cn/news/detail-724789.html
3、實(shí)現(xiàn)代碼
import pymysql
import pandas as pd
import openpyxl
'''
從excel表里讀取數(shù)據(jù)后,再存入到mysql數(shù)據(jù)庫。
需要安裝openpyxl pip install openpyxl
'''
# 讀入數(shù)據(jù):表格列名:user_id,user_name,user_password,is_black
df = pd.read_excel('D:/pythonCode/pythonProject8/case_information_1800_csv.xlsx')
# 連接數(shù)據(jù)庫
db = pymysql.connect(host="localhost", user="root", password="123456", database="medical")
# 獲取游標(biāo)對象
cursor = db.cursor()
# execute(query,args=None) => args為序列,query中必須使用%s做占位符
insert_sql = "insert into case2(case_id,case_name,case_introduction,case_alias,case_medical_insurance,case_infectivity,case_fre_occ_population,case_related_symptoms,case_dep_main,case_dep_sub,case_detail_symptoms,case_therapeutic_method_short,case_therapeutic_method_long,case_information_link) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"
# 遍歷excel表里的數(shù)據(jù)
# len(df) 表格的行數(shù)
for i in range(1, len(df)):
case_id = df.iloc[i, 0] # 第i行第0列(case_id) 第0行數(shù)據(jù)不是列名的那一行,就是真實(shí)數(shù)據(jù)的那一行。
case_name = df.iloc[i, 1] # 第i行第2列(case_name)列
case_introduction = df.iloc[i, 2]
case_alias = df.iloc[i, 3]
case_medical_insurance = df.iloc[i, 4]
case_infectivity = df.iloc[i, 5]
case_fre_occ_population = df.iloc[i, 6]
case_related_symptoms = df.iloc[i, 7]
case_dep_main = df.iloc[i, 8]
case_dep_sub = df.iloc[i, 9]
case_detail_symptoms = df.iloc[i, 10]
case_therapeutic_method_short = df.iloc[i, 11]
case_therapeutic_method_long = df.iloc[i, 12]
case_information_link = df.iloc[i, 13]
# values中的值有個(gè)類型的強(qiáng)制轉(zhuǎn)換,否則會出錯(cuò)
values = (str(case_id), str(case_name), str(case_introduction),str(case_alias),str(case_medical_insurance),str(case_infectivity),str(case_fre_occ_population),
str(case_related_symptoms),str(case_dep_main),str(case_dep_sub),str(case_detail_symptoms),str(case_therapeutic_method_short),str(case_therapeutic_method_long),str(case_information_link))
# 執(zhí)行sql
cursor.execute(insert_sql, values)
# 關(guān)閉游標(biāo)
cursor.close()
# 提交數(shù)據(jù)
db.commit()
# 關(guān)閉數(shù)據(jù)庫
db.close()
?完成。文章來源地址http://www.zghlxwxcb.cn/news/detail-724789.html
到了這里,關(guān)于將Excel表中數(shù)據(jù)導(dǎo)入MySQL數(shù)據(jù)庫的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!