python连接postgresql,查询数据列表,返回字典。完整python代码例子如下
import psycopg2
def get_data(database_info, sql):
conn = psycopg2.connect(database=database_info["database"],
user=database_info["user"],
password=database_info["password"],
host=database_info["host"],
port=database_info["port"])
cur = conn.cursor()
try:
cur.execute(sql)
# 获取表的所有字段名称
coloumns = [row[0] for row in cur.description]
result = [[str(item) for item in row] for row in cur.fetchall()]
return [dict(zip(coloumns, row)) for row in result]
except Exception as ex:
print(ex)
finally:
conn.close()
数据库连接信息
database_info = {
"database": "testinfo",
"user": "postgres",
"password": "***",
"host": "192.168.1.4",
"port": "5432"
}
sql = "SELECT name, threshhold0, threshhold1 from sjy_aqi_threshhold"
data = get_data(database_info, sql)
for item in data:
print(item)
网友评论