使用python从excel批量导入数据到mysql数据库

版权声明:本文为博主原创文章,转载请注明出处:http://blog.csdn.net/sinat_34820292 https://blog.csdn.net/sinat_34820292/article/details/80951501

处理excel推荐使用 openpyxl ,不推荐xlrd和xlwt,因为后两者对xlsx支持非常差劲,并且一个能读不能写,一个能写不能修改,也就是说想要修改一个xls是很繁琐的。

连MySQL数据库使用PyMySQL比较容易操作,本文导入的数据是几十个excel文件,分布于某个目录下的若干子目录下,每个文件十几M到几十M之间。

import pymysql.cursors #用来操作数据库  参考地址: https://pypi.org/project/PyMySQL/#downloads 如果报错请按照这个链接安装 pip3 install PyMySQL
#import xlrd # 用来读excel 参考地址: https://www.cnblogs.com/MrLJC/p/3715783.html
from openpyxl import load_workbook # 可以支持xlsx的工具,https://www.cnblogs.com/anpengapple/p/6399304.html?utm_source=itdadao&utm_medium=referral 
import os # 用来度文件 参考地址: https://www.cnblogs.com/mufenglin/p/7676160.html
import re # 正则表达式模块  参考地址: http://www.runoob.com/python/python-reg-expressions.html

# 连接数据库
connection = pymysql.connect(host='localhost', # 数据库地址
                             user='root',       # 数据库用户名
                             password='root',# 数据库密码
                             db='article',         # 数据库名称
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor)

cursor = connection.cursor()

# 创建数据库
tablename = 'article'        
sql = "CREATE TABLE `"+tablename+"` (`pmid` int(11) NOT NULL,`article_title` varchar(1024) DEFAULT NULL,`author_list` varchar(1024) DEFAULT NULL,`abstract_text` text DEFAULT NULL,`keywords` varchar(1025) DEFAULT NULL,`pmcid` char(255) DEFAULT NULL,`pub_med_pub_date` char(255) DEFAULT NULL,`journal_issue` char(255) DEFAULT NULL,`serch_text` char(255) DEFAULT NULL) ENGINE=MyISAM DEFAULT CHARSET=utf8"
cursor.execute("DROP TABLE IF EXISTS `"+tablename+"`")
cursor.execute(sql)
connection.commit()
count=0
# 遍历目录
basedir = './'
rootdir = os.listdir(basedir)
for subdir in rootdir: # 遍历第一层目录 1 2 3 4 5 6
    if os.path.isdir(subdir):
        subrootdir = os.listdir(basedir+subdir)
        for files in subrootdir: # 遍历第二层目录 如 1下面的目录 
            # print(os.path.splitext(files)[1])
            if os.path.splitext(files)[1]=='.xlsx': # 如果是excel文件
                # data = xlrd.open_workbook(basedir+subdir+'/'+files)
                # table = data.sheets()[0]
                wb = load_workbook(basedir+subdir+'/'+files)
                table = wb.get_sheet_by_name("Sheet1")
                print("导入",basedir+subdir+'/'+files,"数据中,已经导入",count,"条数据")
                ##### 下面的方法是一个excel运行一次插入语句,经验证太慢,一个excel导入耗时超过3分钟
                # thissql = 'insert into '+tablename+' values '
                # for row in range(1,table.nrows):
                #     value = '('
                #     for col in range(0,9):
                #         value += "'"+str(table.cell(row,col).value)+"',"
                #     value = value[:(len(value)-1)]+"),"
                #     thissql +=value                
                # thissql = thissql[:(len(thissql))]
                # cursor.execute(thissql)
                # connection.commit()

                ##### 下面的方法是一行运行一次插入语句
                thissql = 'insert into '+tablename+' values(%s,%s,%s,%s,%s,%s,%s,%s,%s)'
                for row in range(2,table.max_row):
                    cursor.execute(thissql,(#table.cell(row=row,column=0),
                    table.cell(row=row,column=1).value,
                    table.cell(row=row,column=2).value,
                    table.cell(row=row,column=3).value,
                    table.cell(row=row,column=4).value,
                    table.cell(row=row,column=5).value,
                    table.cell(row=row,column=6).value,
                    table.cell(row=row,column=7).value,
                    table.cell(row=row,column=8).value,table.cell(row=row,column=9).value,))
                    count+=1
                connection.commit()

print('批量导入数据完毕,共导入:',count,'条数据')                
# 关闭数据库
connection.close()

猜你喜欢

转载自blog.csdn.net/sinat_34820292/article/details/80951501