如何利用python将表复制到数据库
1、打开表
book = xlrd.open_workbook("收入数据.xls") sheet = book.sheet_by_name("Sheet1")
2、连接数据库
conn = pymysql.connect( host='localhost', user='root', passwd='root', db='sys', port=3306, charset='utf8' )
3、获取游标
cur = conn.cursor()
4、创建插入数据库语句
query = 'insert into income (datetime,ironincome,generalincome,baiincome)values("%s","%s","%s","%s")' # 创建一个for循环迭代读取xls文件每行数据的, 从第二行开始是要跳过标题行 for r in range(1, sheet.nrows): print(sheet.nrows) datetime = sheet.cell(r,0).value print("======================") ironincome = sheet.cell(r,1).value print("ironincome="+str(ironincome),type(ironincome)) generalincome = sheet.cell(r,2).value #打印general_income类型 # print("general_income=" + str(general_income), type(general_income)) print("3hang",generalincome) baiincome = sheet.cell(r,3).value values = (datetime,ironincome,generalincome,baiincome) # 执行sql语句 cur.execute(query%values)
5、关闭数据库
cur.close() conn.commit() conn.close() columns = str(sheet.ncols) rows = str(sheet.nrows)
执行前
执行后
完整代码如下
# -*- coding:utf-8 -*- import xlrd import pymysql #打开数据所在的工作簿,以及选择存有数据的工作表 book = xlrd.open_workbook("收入数据.xls") sheet = book.sheet_by_name("Sheet1") #建立一个MySQL连接 conn = pymysql.connect( host='localhost', user='root', passwd='root', db='sys', port=3306, charset='utf8' ) # 获得游标 cur = conn.cursor() # 创建插入SQL语句 query = 'insert into income (datetime,ironincome,generalincome,baiincome)values("%s","%s","%s","%s")' # 创建一个for循环迭代读取xls文件每行数据的, 从第二行开始是要跳过标题行 for r in range(1, sheet.nrows): print(sheet.nrows) datetime = sheet.cell(r,0).value print("======================") ironincome = sheet.cell(r,1).value print("ironincome="+str(ironincome),type(ironincome)) generalincome = sheet.cell(r,2).value #打印general_income类型 # print("general_income=" + str(general_income), type(general_income)) print("3hang",generalincome) baiincome = sheet.cell(r,3).value values = (datetime,ironincome,generalincome,baiincome) # 执行sql语句 cur.execute(query%values) cur.close() conn.commit() conn.close() columns = str(sheet.ncols) rows = str(sheet.nrows) print ("导入 " +columns + " 列 " + rows + " 行数据到MySQL数据库!")
注意点:
1、表格中不要有空行,要不然表格数据插入到数据库时总是报空(这个错折磨我好久啦!!!)
2、调试时,用debug和print都能方便你很好的解决问题,学着用起来吧!