1. 程式人生 > 資料庫 >Python實現連線postgresql資料庫的方法分析

Python實現連線postgresql資料庫的方法分析

本文例項講述了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()

更多關於Python相關內容感興趣的讀者可檢視本站專題:《Python常見資料庫操作技巧彙總》、《Python數學運算技巧總結》、《Python資料結構與演算法教程》、《Python函式使用技巧總結》、《Python字串操作技巧彙總》、《Python入門與進階經典教程》及《Python檔案與目錄操作技巧彙總》

希望本文所述對大家Python程式設計有所幫助。