我之前没有使用psycopg2,但我正在尝试将光标工厂更改为DictCursor,以便fetchall或fetchone将返回字典而不是列表.
我创建了一个测试脚本,使事情变得简单,只测试这个功能.这是我觉得应该工作的一点代码
import psycopg2
import psycopg2.extras
conn = psycopg2.connect("dbname=%s user=%s password=%s" % (DATABASE, USERNAME, PASSWORD))
cur = conn.cursor(cursor_factory = psycopg2.extras.DictCursor)
cur.execute("SELECT * from review")
res = cur.fetchall()
print type(res)
print res
Run Code Online (Sandbox Code Playgroud)
res变量总是一个列表,而不是我期望的字典.
我实现的当前解决方法是使用此函数来构建字典并运行fetchall通过它返回的每一行.
def build_dict(cursor, row):
x = {}
for key,col in enumerate(cursor.description):
x[col[0]] = row[key]
return d
Run Code Online (Sandbox Code Playgroud)
Python是版本2.6.7,psycopg2是版本2.4.2.
所以我最近安装的SQL Server 2016 CTP3主要用于JSON输出功能.我试图在我的SQL查询中使用它,就像它在MSDN下面的链接中显示的那样.关键字JSON不会变为蓝色并出现错误"JSON'附近的语法不正确"
https://msdn.microsoft.com/en-us/library/dn921882%28v=sql.130%29.aspx?f=255&MSPPError=-2147217396
可能有什么不对?
编辑:我正在使用AdventureWorks DB for SQL Server 2016进行测试.查询是
SELECT * FROM Person.Contact FOR JSON AUTO
Run Code Online (Sandbox Code Playgroud) 我正在使用包含多个表的 postgres 数据库。目标是从获得的查询结果中检索格式化的 JSON。我创建了这个 python 脚本,从表(测试用例)中获取数据集,以便操作查询结果:
\n\nimport psycopg2\nimport json\nfrom time import sleep\nfrom config import config\n\ndef main():\n conn = None\n try:\n params = config()\n conn = psycopg2.connect(**params)\n cur = conn.cursor()\n cur.execute("select * from location")\n row = cur.fetchone()\n\n while row is not None:\n print(row)\n #do field rename, merge(log, lat) and obtained JSON here\n sleep(0.3)\n row = cur.fetchone()\n\n cur.close()\n except (Exception, psycopg2.DatabaseError) as error:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n\nif __name__ == \'__main__\':\n main()\nRun Code Online (Sandbox Code Playgroud)\n\n为了使我的问题更清楚,我在这里制作了一个简化的场景,用 3 个表格来表示手头的任务,如下所示。
\n\nenvironment\n\xe2\x95\x94\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa6\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa6\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\xa6\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x97\n\xe2\x95\x91 …Run Code Online (Sandbox Code Playgroud) 我需要传递一个可以转换的对象$.parseJSON.查询如下所示:
cursor.execute("SELECT earnings, date FROM table")
Run Code Online (Sandbox Code Playgroud)
为了传递可以转换为json的HttpResponse对象,我需要从这里做些什么?