使用psycopg2連接postgresql,首先需要安裝python psycopg2依賴包
pip install psycopg2
然后引用psycopg2,調用psycopg2.connect接口谬墙,實現(xiàn)postgresql連接,進而查詢或更新postgresql數(shù)據(jù)。注意:在插入數(shù)據(jù)時蠢琳,需要commit提交啊终。
conn.commit()
完整python代碼例子如下:
import psycopg2
conn = psycopg2.connect(database="testinfo", user="postgres", password="***", host="192.168.1.4", port="5432")
print("Opened database successfully")
cur = conn.cursor()
cur.execute("SELECT name, threshhold0, threshhold1 from sjy_aqi_threshhold")
rows = cur.fetchall()
for row in rows:
print("NAME = ")
print("threshhold0 = ")
print("threshhold0 = ")
print("Operation done successfully")
conn.close()