使用 executemany() 函数插入数据并解决 'not enough arguments for format string' 错误

该代码旨在使用 executemany() 函数将数据插入到名为 test3 的 SQL 表中。然而,代码中出现了 'not enough arguments for format string' 错误,这是由于传递给 executemany() 函数的参数数量不足造成的。

错误原因:

cur.executemany 函数需要两个参数:

  1. SQL 语句: 包含占位符的 SQL 插入语句。
  2. 可迭代对象: 用于替换占位符的值。该对象应该是一个包含多个元组的可迭代对象,每个元组对应一条记录的数据。

错误代码:

def execl():  # 创建SQL表格
    sql = '''CREATE TABLE IF NOT EXISTS test3 (
                        `序号` INT(11) PRIMARY KEY,
                        `链接` VARCHAR(255),
                        `标题` VARCHAR(255),
                        `时间` DATE
                    )
    '''
    cur.execute(sql)  # 调用之前的cursor来创建表

    data = dict_create()
    for i in data:
        cur.executemany("insert into test3(`序号`, `链接`, `标题`, `时间`) values(%s, %s, %s, %s)",(i[0], i[1], i[2], i[3]))

代码中的 cur.executemany 函数第二个参数传递的是一个元组 (i[0], i[1], i[2], i[3]),而 executemany 函数期望的是一个包含多个元组的可迭代对象。

解决方案:

将 (i[0], i[1], i[2], i[3]) 修改为 [(i[0], i[1], i[2], i[3])],将单个元组封装成一个包含单个元组的列表,这样就能够正确传递参数给 executemany 函数。

修正后的代码:

def execl():  # 创建SQL表格
    sql = '''CREATE TABLE IF NOT EXISTS test3 (
                        `序号` INT(11) PRIMARY KEY,
                        `链接` VARCHAR(255),
                        `标题` VARCHAR(255),
                        `时间` DATE
                    )
    '''
    cur.execute(sql)  # 调用之前的cursor来创建表

    data = dict_create()
    for i in data:
        cur.executemany("insert into test3(`序号`, `链接`, `标题`, `时间`) values(%s, %s, %s, %s)", [(i[0], i[1], i[2], i[3])])

通过以上修改,代码能够正确执行插入操作。

总结:

使用 executemany() 函数插入数据时,需要注意第二个参数必须是包含多个元组的可迭代对象,每个元组对应一条记录的数据。如果参数数量不足,就会导致 'not enough arguments for format string' 错误。

Python 数据库操作:使用 executemany() 函数插入数据

原文地址: https://www.cveoy.top/t/topic/pBjW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录