Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL psycopg2 returns a tuple of strings instead of tuple of tuples?

I have a weird problem, and I'm not too sure how to fix it after searching Google/SO found nothing similar.

When I tried to grab query results from the cursor, it gives me a tuple of tuples, except the tuples are strings? Below is the code.

def queryFeeds(db):
   sql = """SELECT ngo.n_id, feeds.url FROM ngo 
    JOIN feeds ON ngo.n_id = feeds.n_id;"""

   db.c.execute(sql)

   feeds = db.c.fetchall()

   return feeds

The print output is here for the feeds variable returned by the function:

feeds[0]
('(277,http://resultsuk.wordpress.com/feed)',)

feeds[0][0]
'(277,http://resultsuk.wordpress.com/feed)'

type(feeds[0][0])
<type 'str'>

feeds[0][0][0:10]
'(277,http:'

The db is just a class that has the database connection, where db.c is the cursor. Thanks in advance. The deleted data are http: // links that SO won't let me post because of my low reputation.

Cheers,

Lucas

like image 831
user2524674 Avatar asked Apr 17 '15 04:04

user2524674


People also ask

What is a dead tuple?

As seen in the above examples, every such record that has been deleted but is still taking some space is called a dead tuple. Once there is no dependency on those dead tuples with the already running transactions, the dead tuples are no longer needed. Thus, PostgreSQL runs VACUUM on such Tables.

Is Psycopg2 connection thread safe?

Thread and process safetyThe Psycopg module and the connection objects are thread-safe: many threads can access the same database either using separate sessions and creating a connection per thread or using the same connection and creating separate cursors. In DB API 2.0 parlance, Psycopg is level 2 thread safe.

Is Psycopg2 asynchronous?

Psycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY.

Does Psycopg2 need PostgreSQL?

Prerequisites. The current psycopg2 implementation supports: Python versions from 3.6 to 3.11. PostgreSQL server versions from 7.4 to 15.


1 Answers

Remove the parentheses from the fields in the SELECT clause.

I had this same issue (though with a RETURNING clause instead of a SELECT), and the comment by @user2524674 deserves to be an answer. Before the question was edited, the fields in the SELECT clause were surrounded by parentheses, i.e.

SELECT (ngo.n_id, feeds.url)

and the result returned is a string rather than an actual tuple. Changing this to

SELECT ngo.n_id, feeds.url

causes psycopg2 to return an actual tuple of values.

like image 98
abeboparebop Avatar answered Oct 16 '22 23:10

abeboparebop