[英]Accessing test PostgreSQL database from python
我似乎无法正确连接并从python中的测试postgreSQL数据库中提取。 我使用Homebrew安装了PostgreSQL。 这是我从终端访问数据库表和值的方式:
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)
但是,当尝试使用以下代码从python访问它时,它不起作用。 有什么建议么?
########################################################################################
# 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
应该说:结果:有效!
您需要获取结果。
从文档:
[
execute()
-]方法返回None 。 如果执行了查询,则可以使用fetch*()
方法检索返回的值。
例:
result = cursor.fetchall()
以供参考:
请注意,(不同于psql
) psycopg2
在事务中包装了所有内容。 因此,如果您打算对数据库发出持久性更改( INSERT
, UPDATE
, DELETE
等),则需要明确地提交它们。 否则,连接对象被销毁时,更改将自动回滚。 在此处阅读有关该主题的更多信息:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.