pythonpostgresqlpsycopg2

psycopg2 not returning results


I am trying to use psycopg2 with my postgresql database just running on my local machine can't get it to return results no matter what I try. It seems to connect to the database ok, since if I alter any of the config parameters it throws errors, however, when I run seemingly valid and result worthy queries, I get nothing.

My db is running and definitely has a table in it:

postgres=# \c
You are now connected to database "postgres" as user "postgres".
postgres=# select * from foos;
  name   | age 
---------+-----
 Sarah   |  23
 Michael |  35
 Alice   |  12
 James   |  20
 John    |  52
(5 rows)

My python code connects to this database but no matter what query I run, I get None:

Python 2.7.3 (default, Apr 10 2013, 06:20:15) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import psycopg2
>>> conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost'")
>>> cur = conn.cursor()
>>> print cur.execute("select * from foos;")
None
>>> print cur.execute("select * from foos")
None
>>> print cur.execute("select name from foos")
None
>>> print cur.execute("select f.name from foos f")
None

Am I doing something obviously wrong? How can I start debugging this, I don't know where to start since it connects just fine?


Solution

  • cursor.execute prepares and executes query but doesn’t fetch any data so None is expected return type. If you want to retrieve query result you have to use one of the fetch* methods:

    print cur.fetchone()
    
    rows_to_fetch = 3
    print cur.fetchmany(rows_to_fetch)
    
    print cur.fetchall()