我查看了许多堆栈溢出帖子,大多数帖子都告诉我在插入VALUES (%s)
时需要使用tuple
或list
。我尝试了列表和元组,但仍然得到相同的错误: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
格式?
我该如何消除这个错误呢
使用
cursor.execute
执行INSERT
语句时VALUES
子句中的占位符数匹配cursor.execute
的第二个参数中的元素数必须与VALUES
子句中的占位符数匹配所以
错误,因为插入了三列,但只有两个值占位符
及
错误,因为第二个参数中的值数量与
VALUES
子句中的占位符数量不匹配相关问题 更多 >
编程相关推荐