本文實例講述了Python實現連接postgresql數據庫的方法。分享給大家供大家參考,具體如下:
python可以通過第三方模塊連接postgresql. 比較有名的有psycopg2和python3-postgresql
(一)psycopg2
ubuntu下安裝
1
|
sudo apt-get install python3-psycopg2 |
創建一個test.py文件
1
2
3
4
5
6
7
8
9
10
|
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() |
運行后顯示如下
1
|
[( 2 , 'jack' , 'girl' ), ( 1 , 'max' , 'boy ' ), ( 3 , 'kate' , 'girl' )] |
(二)python3-postgresql
ubuntu下安裝
1
|
sudo apt-get install python3-postgresql |
創建文件并運行
1
2
3
4
5
6
7
|
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() |
希望本文所述對大家Python程序設計有所幫助。
原文鏈接:http://www.cnblogs.com/jmlovepython/p/5023794.html