4.python實現(xiàn)Excel導(dǎo)入Mysql數(shù)據(jù)庫

1.環(huán)境介紹:

  • python版本:3.6.4
  • pymysql: 0.8.0
  • xlrd: 1.1.10

pymysql安裝
pip install pymysql

xlwt安裝
pip install xlrd

2.創(chuàng)建一個新表并導(dǎo)入excel數(shù)據(jù)

代碼示例
注意:telphone為數(shù)據(jù)庫名;yhtest為新創(chuàng)建的表名字

import pymysql
import xlrd

# 讀取excel中內(nèi)容到數(shù)據(jù)庫
workbook = xlrd.open_workbook('./yhxt.xls')
sheet = workbook.sheet_by_index(0)
data_list= []
nrows = sheet.nrows # 行數(shù)
ncols = sheet.ncols # 列數(shù)
fo = []

fo.append(sheet.row_values(0))
for i in range(1,nrows):
    data_list.append(sheet.row_values(i))

conn=pymysql.connect(host='localhost',user='root',passwd='password',db='telphone',charset='utf8')  
cursor=conn.cursor()  
#創(chuàng)建table  
cursor.execute("create table yhtest("+fo[0][0]+" varchar(100));")  
#創(chuàng)建table屬性  
for i in range(1,ncols):  
    cursor.execute("alter table yhtest add "+fo[0][i]+" varchar(100);")  
val=''  
for i in range(0,ncols):  
    val = val+'%s,'  
print(data_list)  
  
cursor.executemany("insert into yhtest values("+val[:-1]+");" ,data_list)  
conn.commit()
導(dǎo)入新建yhtest表

3.導(dǎo)入原有的表中(excel數(shù)據(jù)導(dǎo)入已有的表中,不需要創(chuàng)建新表)

代碼示例
注意:telphone為數(shù)據(jù)庫名;login為原有的表名字

import pymysql
import xlrd

# 讀取excel中內(nèi)容到數(shù)據(jù)庫
workbook = xlrd.open_workbook('./yhxt.xls')
sheet = workbook.sheet_by_index(0)
data_list= []
nrows = sheet.nrows # 行數(shù)
ncols = sheet.ncols # 列數(shù)
fo = []

fo.append(sheet.row_values(0))
for i in range(1,nrows):
    data_list.append(sheet.row_values(i))

conn=pymysql.connect(host='localhost',user='root',passwd='password',db='telphone',charset='utf8')  
cursor=conn.cursor()

# #創(chuàng)建table  
# cursor.execute("create table yhtest("+fo[0][0]+" varchar(100));")

# #創(chuàng)建table屬性  
# for i in range(1,ncols):  
#     cursor.execute("alter table yhtest add "+fo[0][i]+" varchar(100);")  

val=''  
for i in range(0,ncols):  
    val = val+'%s,'  
print(data_list)  
  
cursor.executemany("insert into login values("+val[:-1]+");" ,data_list)  
conn.commit()
導(dǎo)入原有(已有)login表
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容