简体   繁体   中英

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?

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?!

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM