psycopg2:TypeError:在字符串格式化过程中未转换所有参数

2024-09-28 13:08:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我查看了许多堆栈溢出帖子,大多数帖子都告诉我在插入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列表,尽管在我看来,使用索引(数据[0]、数据[1]等)简单地遍历data列表将得到相同的结果

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

另外,如果您注意到,这里的字符串格式是旧的(指VALUES (%s))。在这种情况下如何使用f格式? 我该如何消除这个错误呢


Tags: the数据列表databytesconndropoutsent
1条回答
网友
1楼 · 发布于 2024-09-28 13:08:21

使用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子句中的占位符数量不匹配

相关问题 更多 >

    热门问题