美文网首页
python连接查询postgresql返回字典

python连接查询postgresql返回字典

作者: reco171 | 来源:发表于2019-01-18 10:04 被阅读0次

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)

相关文章

网友评论

      本文标题:python连接查询postgresql返回字典

      本文链接:https://www.haomeiwen.com/subject/kjkvdqtx.html