我正在尝试将数据从Excel导入到MySQl,下面是我的代码,这里的问题是它只将Excel表中的最后一行写入MySQl数据库,我希望它导入Excel表中的所有行。
import pymysql
import xlrd
book = xlrd.open_workbook('C:\SqlExcel\Backup.xlsx')
sheet = book.sheet_by_index(0)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='test')
cursor = connection.cursor()
query = """INSERT INTO report_table (FirstName, LastName) VALUES (%s, %s)"""
for r in range(1, sheet.nrows):
fname = sheet.cell(r,1).value
lname = sheet.cell(r,2).value
values = (fname, lname)
cursor.execute(query, values)
connection.commit()
cursor.close()
connection.close()
最佳答案
您的代码当前仅存储最后一对,并将其写入数据库。您需要在循环内调用 fname
和 lname
并将每一对单独写入数据库。
您可以将代码修改为:
import pymysql
import xlrd
book = xlrd.open_workbook('C:\SqlExcel\Backup.xlsx')
sheet = book.sheet_by_index(0)
# Connect to the database
connection = pymysql.connect(host='localhost',
user='root',
password='',
db='test',
autocommit=True)
cursor = connection.cursor()
query = """INSERT INTO report_table (FirstName, LastName) VALUES (%s, %s)"""
# loop over each row
for r in range(1, sheet.nrows):
# extract each cell
fname = sheet.cell(r,1).value
lname = sheet.cell(r,2).value
# extract cells into pair
values = fname, lname
# write pair to db
cursor.execute(query, values)
# close everything
cursor.close()
connection.close()
注意:您可以在连接阶段设置autocommit=True
。 PyMySQL 默认禁用自动提交。这意味着您不必在查询后调用 cursor.commit()
。
关于python - 从excel导入到mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50719532/