gpt4 book ai didi

python - 从 python 访问测试 PostgreSQL 数据库

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:14 25 4
gpt4 key购买 nike

我似乎无法正确连接并从 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

它应该说:结果:它有效!

最佳答案

您需要获取结果。

来自文档:

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

示例:

result = cursor.fetchall()

供引用:

请注意(与 psql 不同)psycopg2 将任何内容包装在事务中。因此,如果您打算对数据库发出持久更改(INSERTUPDATEDELETE...),您需要显式提交它们。否则,当连接对象被销毁时,更改将自动回滚。在这里阅读有关该主题的更多信息:

关于python - 从 python 访问测试 PostgreSQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27798185/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com