【发布时间】:2019-03-10 21:41:10
【问题描述】:
在 psycopg2 中,有没有办法让光标以字符串而不是 JSON(或字符串)格式而不是字典对象的形式返回结果?
示例
# connect to database
conn = psycopg2.connect(host=host, port=port, user=usr, password=passwd, dbname=dbn)
cur = conn.cursor(cursor_factory=RealDictCursor)
# CREATE table and INSERT
cur.execute("CREATE TABLE t1(c char, i int);")
cur.execute("INSERT INTO t1(c, i) VALUES ('a', 1), ('b', 2), ('c', 3)");
# Execute query
cur.execute("SELECT COUNT(*) FROM t1;")
output1 = cur.fetchall()
cur.execute("SELECT * FROM t1;")
output2 = cur.fetchall()
Expect - 格式化为 JSON 或字符串的对象列表
output1 - ['{"count": 3}']
output2 - ['{"c": "a", "i": 1}', '{"c": "b", "i": 2}', '{"c": "c", "i": 3}']
实际 - 字典对象列表
output1 - [{'count': 3}]
output2 - [{'c': 'a', 'i': 1}, {'c': 'b', 'i': 2}, {'c': 'c', 'i': 3}]
我目前正在使用 JSON 模块将每个对象转换为 JSON,但我想知道是否有更简单的方法(即在 psycopg2 中)。
【问题讨论】:
-
output1 = json.dumps(cur.fetchall())还不够简单? -
@klin,我举了一个简单的例子,但实际情况包含 datetime.datetime 对象,因此如果我使用你的方法,我会出错。这意味着为了使用 json 函数,我必须更新列表,然后转换 JSON...
标签: python-3.x postgresql psycopg2