我正在尝试使用 python 从 Excel 工作表导入 MySQL 表中的数据。我想要将文件夹中的大约 250 个文件导入到 MySQL。代码可以运行并导入数据,但每个文件花费的时间太长。
import xlrd
import MySQLdb
import os
import glob
database=MySQLdb.connect()
for filepath in glob.iglob('folder\\*.xlsx')
path=filepath
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)
cursor=database.cursor()
query="""insert into tx_shape_files(col1,col2,...col6) values(%s,%s,%s,%s,%s,%s)"""
for r in range(1,sheet.nrows):
col1=sheet.cell(r,0).value
col2=sheet.cell(r,1).value
col3=sheet.cell(r,2).value
col4=sheet.cell(r,3).value
col5=sheet.cell(r,4).value
col6=sheet.cell(r,5).value
values=(col1,col2,...col6)
cursor.execute(query,values)
cursor.close()
database.commit()
print("Done")
columns=str(sheet.ncols)
rows=str(sheet.nrows)
print("Imported " +columns+ " columns and "+ rows+" rows to MYSQL")
database.close()
此代码将数据从 Excel 导入到 RDS MySql 数据库所需的时间太长。
请帮助我优化我的代码。
最佳答案
尝试只访问数据库一次。您可以在单个插入语句中插入多行,如下所示。
INSERT INTO tbl_name
(a,b,c)
VALUES
(1,2,3),
(4,5,6),
(7,8,9);
在内部for循环之外执行cursor.execute()语句以一次执行多行查询。添加代码以供引用。
import xlrd
import MySQLdb
import os
import glob
database=MySQLdb.connect()
for filepath in glob.iglob('folder\\*.xlsx')
path=filepath
workbook = xlrd.open_workbook(path)
sheet = workbook.sheet_by_index(0)
cursor=database.cursor()
query="""insert into tx_shape_files(col1,col2,...col6) values(%s,%s,%s,%s,%s,%s)"""
all_values = []
for r in range(1,sheet.nrows):
col1=sheet.cell(r,0).value
col2=sheet.cell(r,1).value
col3=sheet.cell(r,2).value
col4=sheet.cell(r,3).value
col5=sheet.cell(r,4).value
col6=sheet.cell(r,5).value
values=(col1,col2,...col6)
all_values.append(values)
cursor.execute(query, all_values)
cursor.close()
database.commit()
print("Done")
columns=str(sheet.ncols)
rows=str(sheet.nrows)
print("Imported " +columns+ " columns and "+ rows+" rows to MYSQL")
database.close()
关于python - 尝试将Excel文件中的数据导入RDS MySQL表中,插入时间太长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55753283/