Skip to content

Instantly share code, notes, and snippets.

@rsudip90
Last active October 26, 2019 23:05
Show Gist options
  • Save rsudip90/a628d3db2dd108aa3669223323e62f76 to your computer and use it in GitHub Desktop.
Save rsudip90/a628d3db2dd108aa3669223323e62f76 to your computer and use it in GitHub Desktop.
MySQL JSON type data handling in python
import mysql.connector
import json
config = {
"user": "",
"password": "",
"host": "localhost",
"database": "test",
"use_pure": True,
}
json_data = {
"Name": "Harry Potter",
"Email": "harry@earth.world",
"CellPhone": "xxx0000xxx",
"Address": "Earth, Milky Way!!"
}
b_data = json.dumps(json_data)
docID = 1
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor(prepared=True)
# stmt = "UPDATE JSONDoc SET Data = JSON_REPLACE(Data, CONCAT('$', %s), CAST(%s AS JSON)) WHERE DocID=%s"
stmt = "UPDATE JSONDoc SET Data = JSON_REPLACE(Data, CONCAT('$', %s), %s) WHERE DocID=%s"
cursor.execute(stmt, ("", b_data, docID))
cnx.commit()
cursor.close()
cnx.close()
Copy link

ghost commented Oct 26, 2019

This doesn't work because how exactly is the interpreter going to understand that '{"Foo": "Bar}' is an object and not a primitive string?

Firstly, if you just want to set the Data column's "root" value to be an object, just use SET Data = %s.

If you want the query to allow setting arbitrary path values, don't use JSON_REPLACE, as it can only replace existing paths. Use JSON_SET, and be sure to return a json_document by calling JSON_EXTRACT(json_document,path):

UPDATE JSONDoc SET Data = JSON_SET(Data,CONCAT('$',%s),JSON_EXTRACT(%s,'$')) WHERE DocID = %s

Again, for setting the whole document, you don't need the JSON functions at all.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment