1

I can't seem to correctly connect and pull from a test postgreSQL database in python. I installed PostgreSQL using Homebrew. Here's how I have been accessing the database table and value from the terminal:

xxx-macbook:~ xxx$ psql
psql (9.4.0)
Type "help" for help.

xxx=# \dn
 List of schemas
  Name  |  Owner  
--------+---------
 public | xxx
(1 row)

xxx=# \connect postgres
You are now connected to database "postgres" as user "xxx".
postgres=# SELECT * from test.test;
  coltest  
-----------
 It works!
(1 row)

But when trying to access it from python, using the code below, it doesn't work. Any suggestions?

########################################################################################
# Importing variables from PostgreSQL database via SQL commands

db_conn = psycopg2.connect(database='postgres',
                           user='xxx')

cursor = db_conn.cursor()

#querying the database
result = cursor.execute("""
Select * From test.test
""")

print "Result: ", result
>>> Result: None

It should say: Result: It works!

0

1 Answer 1

1

You need to fetch the results.

From the docs:

The [execute()-]method returns None. If a query was executed, the returned values can be retrieved using fetch*() methods.

Example:

result = cursor.fetchall()

For reference:

Note that (unlike psql) psycopg2 wraps anything in transactions. So if you intend to issue persistent changes to the database (INSERT, UPDATE, DELETE, ...) you need to commit them explicitly. Otherwise changes will be rolled back automatically when the connection object is destroyed. Read more on that topic here:

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.