7

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

user2524674
  • 73
  • 2
  • 5

1 Answers1

12

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.

abeboparebop
  • 7,396
  • 6
  • 37
  • 46