[英]“TypeError: tuple indices must be integers, not str” - When using a tuple with integer indices
So there's a strange error I'm having. 所以我有一个奇怪的错误。 I'm trying to use psycopg2 python library to insert a few values into the database. 我正在尝试使用psycopg2 python库将一些值插入数据库。
I'm passing a tuple (pages) consisting of two values into the following function: 我正在将由两个值组成的元组(页面)传递给以下函数:
def insertPages(self,pages):
cursor = self.connection.cursor()
for page in pages:
try:
tupl = (page[0],page[1])
print(str(tupl), str(tupl[0]),str(tupl[1]))
cursor.execute("""INSERT INTO page(page_id,page_url) VALUES(%()s, %()s)""",tupl)
self.connection.commit()
except psycopg2.Error as error:
safePrint("Database error when inserting page:" + str(error.pgcode) + str(error))
However, no matter whether I pass the 'pages' tuple into execute, or whether i pass the new 'tupl' tuple, I'm still receiving the same error: 但是,无论我是否将'pages'元组传递给execute,还是将新的'tupl'元组传递给我,我仍然会收到相同的错误:
(0, 'page_1') 0 page_1
Traceback (most recent call last):
File "/Users/netaro/EclipseWorkspace/PageRanker/src/main.py", line 184, in <module>
main()
File "/Users/netaro/EclipseWorkspace/PageRanker/src/main.py", line 179, in main
postgresController.insertPages(pageController.getPageArray())
File "/Users/netaro/EclipseWorkspace/PageRanker/src/main.py", line 102, in insertPages
cursor.execute("""INSERT INTO page(page_id,page_url) VALUES(%()s, %()s)""",tupl)
TypeError: tuple indices must be integers, not str
But that's strange, as I;m already using nothing else than simple tuples... 但这很奇怪,因为我已经在使用简单的元组了...
I have no experience with Psycopg2, but looking at the doc page , it seems like your use of parentheses in %()s
may indicate that you are using named arguments , in which case you need to provide a dict, rather than a tuple, as the second argument. 我没有使用Psycopg2的经验,但是在doc页面上 ,看来您在%()s
使用括号可能表明您使用的是命名参数 ,在这种情况下,您需要提供一个dict,而不是元组,作为第二个论点。
Try changing the line to: 尝试将行更改为:
cursor.execute("INSERT INTO page(page_id,page_url) VALUES(%s, %s);", tupl)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.