python - 从excel导入到mysql

标签 python mysql excel

我正在尝试将数据从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()

最佳答案

您的代码当前仅存储最后一对,并将其写入数据库。您需要在循环内调用 fnamelname 并将每一对单独写入数据库。

您可以将代码修改为:

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/

相关文章:

python - 为什么 pandas 有时在选择列时似乎会更改字符串编码?

python - 在 Keras/Tensorflow 自定义损失函数中使用额外的 *trainable* 变量

mysql - 级联删除时触发调用

php - 在 php 中获取 url id 并在 html 中显示结果

excel - Excel 工作表中的独立计时器宏

python - Pandas dataframe read_excel 不会将左上角的空白单元格视为列?

python - 实现 Jedi 可以理解的惰性属性

python - spacy-pytorch-transformers 中的标记向量是如何计算的

mysql - 有人可以向我解释一下这个基数参与约束吗?

arrays - 数组不一致