使用psycopg2连接postgresql,首先需要安装python psycopg2依赖包
pip install psycopg2
然后引用psycopg2,调用psycopg2.connect接口,实现postgresql连接,进而查询或更新postgresql数据。注意:在插入数据时,需要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()