简体   繁体   English

从python访问测试PostgreSQL数据库

[英]Accessing test PostgreSQL database from python

I can't seem to correctly connect and pull from a test postgreSQL database in python. 我似乎无法正确连接并从python中的测试postgreSQL数据库中提取。 I installed PostgreSQL using Homebrew. 我使用Homebrew安装了PostgreSQL。 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. 但是,当尝试使用以下代码从python访问它时,它不起作用。 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 . [ execute() -]方法返回None If a query was executed, the returned values can be retrieved using fetch*() methods. 如果执行了查询,则可以使用fetch*()方法检索返回的值。

Example: 例:

result = cursor.fetchall()

For reference: 以供参考:

Note that (unlike psql ) psycopg2 wraps anything in transactions. 请注意,(不同于psqlpsycopg2在事务中包装了所有内容。 So if you intend to issue persistent changes to the database ( INSERT , UPDATE , DELETE , ...) you need to commit them explicitly. 因此,如果您打算对数据库发出持久性更改( INSERTUPDATEDELETE等),则需要明确地提交它们。 Otherwise changes will be rolled back automatically when the connection object is destroyed. 否则,连接对象被销毁时,更改将自动回滚。 Read more on that topic here: 在此处阅读有关该主题的更多信息:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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