Last active
October 26, 2019 23:05
-
-
Save rsudip90/a628d3db2dd108aa3669223323e62f76 to your computer and use it in GitHub Desktop.
MySQL JSON type data handling in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mysql.connector | |
import json | |
config = { | |
"user": "", | |
"password": "", | |
"host": "localhost", | |
"database": "test", | |
"use_pure": True, | |
} | |
json_data = { | |
"Name": "Harry Potter", | |
"Email": "[email protected]", | |
"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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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. UseJSON_SET
, and be sure to return ajson_document
by callingJSON_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.