Domanda

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.

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:

(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...

È stato utile?

Soluzione

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.

Try changing the line to:

cursor.execute("INSERT INTO page(page_id,page_url) VALUES(%s, %s);", tupl)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top