簡體   English   中英

從python訪問測試PostgreSQL數據庫

[英]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()

以供參考:

請注意,(不同於psqlpsycopg2在事務中包裝了所有內容。 因此,如果您打算對數據庫發出持久性更改( INSERTUPDATEDELETE等),則需要明確地提交它們。 否則,連接對象被銷毀時,更改將自動回滾。 在此處閱讀有關該主題的更多信息:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM