使用python将excel中的数据导入mysql数据库

对表的更新使用导入工具觉得太慢,正好最近在看python,试着玩玩,不好勿喷
环境:
Python3.7(windows环境)
Xlrd、pymysql模块(可能需要下载 )
准备:
excel的book需要和mysql表中字段的顺序相同
excel表的名称第一部分在数据库表中可体现(不一样的话修改查询【excel与数据库中表关联的那个】的条件字段就行)
excel的book名称在数据库表中可体现
代码

import xlrd
import os
import re
import pymysql
os.chdir('D:\\test')
print("当前工作目录为:",end=" ")
print(os.getcwd(),end="\n")
if(input("是否需要切换目录?(Y/N)" )in "Y|y"):
    dir=input("输入切换的目录:")
    try:
        os.chdir(dir)
    except Exception as e:
        print(e)
    finally:
        print("当前工作目录为:",end=" ")
        print(os.getcwd(),end="\n")
"""开始选择传输表格"""
log={}
nu=0
while 1:
	print("可被处理的表格:")
	suit=[x for x in os.listdir() if re.search("xlsx$",x)]
	suit_dict={}
	for i in range(len(suit)):
			suit_dict[i]=suit[i]
			print(i,suit_dict[i])
	
	while(1):
		tablen=input("输入选用table的编号:")
		if tablen.isdigit() :
			if   int(tablen) in list(suit_dict.keys()):
				book=xlrd.open_workbook(suit_dict[int(tablen)])
				book_name=suit_dict[int(tablen)]
				break
			else:
				print("输入错误,选择编号内的数字")
	
		else:
			print("输入数字")
	"""
	完成选择传输表格,开始选择传输sheet
	"""
	sheetName=book.sheet_names()
	liebiao_dict={}
	for i in range(len(sheetName)):
		liebiao_dict[i]=sheetName[i]
	print(liebiao_dict)
	c=0
	while(1):
		sheetn=input("输入选用的sheet编号:")
		if sheetn.isdigit() :
			if   int(sheetn) in list(liebiao_dict.keys()):
				sheet=book.sheet_by_name(liebiao_dict[int(sheetn)])
				break
			else:
				print(type(sheetn))
				c+=1
				if(c>=2):
					break
				print("输入错误,请选择编号内的数字")
	
		else:
			print("请输入数字")
	"""
	完成选择传输sheet,开始连接数据库,择定操作的table
	"""
	print("正在对Excel文件"+book_name+"  "+"的 "+sheet.name+"进行处理")
	query="select table_name from information_schema.tables where table_schema='mstest' and table_name like ""'%"+sheet.name+"%'"" and table_name like ""'%"+book_name.split("-")[0]+"%'"""
	conn=pymysql.connect(host='localhost',user='root',passwd='root',db='mstest')
	cur=conn.cursor()
	num=cur.execute(query)
	tb={}
	table=""
	if(num==1):
		table=str([r for r in cur if num==1]).split("'")[1]
	elif(num>1):
		for index,r  in enumerate(cur):
			r=str(r).split("'")[1]
			tb[index]=r
			print(index,r)
		while(1):
			ttab=input("请选择要操作表的编号:")
			if ttab.isdigit() :
				if(int(ttab)in list(tb.keys())):
					table=tb[int(ttab)]
					break
				else:
					print("输入错误")
					continue
			else:
				print("输入数字")
	else:
		print("查询字段有误,降维处理")
		query="select table_name from information_schema.tables where table_schema='mstest' and table_name like ""'%"+book_name.split("-")[0]+"%'"""
		num=cur.execute(query)
		for index,r  in enumerate(cur):
			r=str(r).split("'")[1]
			tb[index]=r
			print(index,r)
		while(1):
			ttab=input("选择要操作表的编号:")
			if ttab.isdigit() :
				if(int(ttab)in list(tb.keys())):
					table=tb[int(ttab)]
					break
				else:
					print("输入错误")
					continue
			else:
				print("输入数字")
	print("正在对库中表格:"+table+" 进行处理")
	"""
	完成表格的选择,对数据进行跟新
	"""
	if(input("是否需要删除库中表"+table+"的数据(Y/N)")in "Yy"):
		cur.execute("truncate table "+table)
	que="desc "+table
	cur.execute(que)
	column={}
	cnum=0
	col=[]
	for index,rr in enumerate(cur):
		column[index]=str(list(rr)).split("'")[1]
		col.append(column[index])
	for r in range(1,sheet.nrows):
		cnum+=1
		sj=""
		for f in range(0,len(col)):
			sj=sj+col[f]+"=\""+str(sheet.cell(r,f).value)+"\","
		query="insert into "+table+" set "+sj[:-1]+""
		cur.execute(query)
	conn.commit()
	cur.execute("select count(1) from "+table+"")
	tnum=str([r for r in cur]).split("(")[1].split(",")[0]
	if(input("是否选择预览前10条数据(Y/N)?") in "Y,y"):
		cur.execute("select *from "+table+" limit 10")
		for i in cur:
			print(i)
	logdetail="数据传输完成,从excel中取出"+str(cnum)+"条数据,表"+table+" 共有 "+tnum+" 条数据"
	print(logdetail)
	cur.close()
	log[nu]=logdetail
	nu+=1
	if(input("是否退出(Y/N)") in "Yy"):
		break;
	else:
		continue
conn.close()
print("输出本次操作:")
for i in range(len(log)):
	print("  "+log[i])


运行结果
使用python将excel中的数据导入mysql数据库_第1张图片

你可能感兴趣的:(python)