简体   繁体   中英

Accessing test PostgreSQL database from python

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!

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM