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()