Python连接postgresql并以字典返回查询结果
一、列表嵌套元组返回
import psycopg2
# 基本查询,以列表嵌套元组返回[(1, 2, 3), (2, 3, 4), ...]
def execute(sql):
conn = psycopg2.connect(database=db, user=user, password=password, host=host, port=port)
cur = conn.cursor()
try:
cur.execute(sql)
rows = cur.fetchall()
finally:
cur.close()
conn.close()
return rows
测试用例:
h_table = "hr_department"
# execute和下例execute_dict在文件a中,此处将文件a引入并别名cr,调用函数与变量
res = cr.execute("select * from %s order by id desc limit 3" % h_table)
print(res)
返回如下:
[(2855, '管理部门', '管理部门', True, 59, None, None, None, None, None, 10149, datetime.datetime(2020, 11, 17, 10, 29, 29, 471786), 10149, datetime.datetime(2020, 11, 17, 10, 32, 1, 956590), 'GL01', 1, None, True, 32468, True, None, False, 0),
(2854, '张部门', '张部门', True