python連接postgresql數據庫


python可以通過第三方模塊連接postgresql. 比較有名的有psycopg2  和python3-postgresql

(一)psycopg2

ubuntu下安裝

sudo apt-get install python3-psycopg2

創建一個test.py文件

import psycopg2
# 數據庫連接參數
conn = psycopg2.connect(database="test1", user="jm", password="123", host="127.0.0.1", port="5432")
cur = conn.cursor()

cur.execute("SELECT * FROM a1;")
rows = cur.fetchall()        # all rows in table
print(rows)

 conn.commit()
 cur.close()
 conn.close()

 

運行后顯示如下

[(2, 'jack', 'girl'), (1, 'max', 'boy '), (3, 'kate', 'girl')]

(二)python3-postgresql

ubuntu下安裝

sudo apt-get install python3-postgresql

 創建文件並運行

import postgresql

  #('pq://用戶名:密碼@localhost:5432/數據庫名')
db = postgresql.open('pq://jm:123@localhost:5432/test1')
ps=db.prepare("select * from a1")

print(ps())

ps.close()
db.close()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM