psycopg2: TypeError: not all arguments converted during string formatting

psycopg2: TypeError: not all arguments converted during string formatting

我查看了许多堆栈溢出帖子,其中大部分告诉我在插入 VALUES (%s) 时需要使用 tuplelist。我尝试了列表和元组,但仍然出现相同的错误:not all arguments converted during string formatting。下面是用于将一些数据插入 PostgreSQL 数据库的函数代码:

sql = '''
    INSERT INTO immediate_info (
    bytes_sent,
    bytes_recv,
    packets_sent,
    packets_recv,
    errin,
    errout,
    dropin,
    dropout)
    VALUES (%s);
'''

conn = None

bytes_recv, bytes_sent, packets_sent, packets_recv, errin, errout, dropin, dropout = data

try:
    conn = psycopg2.connect('all the connect stuff')
    # create a new cursor
    cur = conn.cursor()
    # execute the INSERT statement
    cur.execute(sql, (bytes_recv, bytes_sent, packets_sent, packets_recv, errin, errout, dropin, dropout,))
    # commit the changes to the database
    conn.commit()
    # close communication with the database
    cur.close()

except (Exception, psycopg2.DatabaseError) as error:

    print(error)

finally:
    if conn is not None:
        conn.close()

正如我上面提到的,我也尝试过使用列表。这次我决定首先解压缩 data 列表,但在我看来,只需使用索引(data[0]、data[1] 等)遍历 data 列表,导致相同的结果。

data 包含一些用于测量我计算机带宽的网络信息。它的所有内容都是 int 格式。

另外,如果你注意到了,这里的字符串格式是旧的(参考VALUES (%s))。在这种情况下如何使用 f 格式? 我该如何摆脱这个错误?

当使用 cursor.execute

执行 INSERT 语句时
  • 插入的列数必须与 VALUES 子句中的占位符数相匹配
  • cursor.execute 的第二个参数中的元素数量必须与 VALUES 子句中的占位符数量相匹配

所以

cursor.execute("""INSERT INTO foo (bar, baz, quux) VALUES (%s, %s)""", args)

是错误的,因为插入了三列,但只有两个值占位符

cursor.execute("""INSERT INTO foo (bar, baz, quux) VALUES (%s, %s, %s)""",
               ('a', 'b', 'c', 'd'))

是错误的,因为第二个参数中的值数量与 VALUES 子句中的占位符数量不匹配。