[英]How to store a json object as string in SQL database
Using python, json, and pyodbc, is there a python function to store a json object in a Text field in a SQL database? 使用python,json和pyodbc,是否有python函数将json对象存储在SQL数据库的Text字段中?
For example: 例如:
cnxn = pyodbc.connect( MY CONNECTION STRING )
cursor = cnxn.cursor()
cursor.execute("UPDATE TABLE1 SET FIELD1 = '" + json.dumps(pythonDictionary) + "' WHERE FIELD2 = 'some value'")
I always get syntax error because i am not properly escaping the special symbols in the json object, i simply want that json dump to be converted to proper sql string, is there a function in python to do that?! 我总是会收到语法错误,因为我没有正确地转义json对象中的特殊符号,我只是希望将json转储转换为正确的sql字符串,python中是否有一个函数可以做到这一点?
Instead of escaping yourself, you should just use parameterized values: 而不是逃避自己,您应该只使用参数化的值:
cursor.execute("UPDATE TABLE1 SET FIELD1 = ? WHERE FIELD2 = 'some value'", (json.dumps(pythonDictionary)) )
How to use variables in SQL statement in Python? 如何在Python的SQL语句中使用变量?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.