1

Basically, I have a MySQL table like this:

CREATE TABLE markets (
    id INTEGER AUTO_INCREMENT NOT NULL,
    root_symbol VARCHAR(64) NOT NULL, 
    metadata JSON NOT NULL, 
    PRIMARY KEY (id)
);

The metadata column contains a JSON document like this:

metadata = {
    'tick_size': 0.01, 
    'currency': 'USD'
}

In Python, the following 2 lines work:

cur.execute("SELECT root_symbol FROM markets WHERE JSON_EXTRACT(metadata, '$.currency') = 'USD'")
cur.execute("SELECT root_symbol FROM markets WHERE JSON_EXTRACT(metadata, '$.tick_size') = 0.25")

Yet when parameterized, these 2 don't:

cur.execute("SELECT root_symbol FROM markets WHERE JSON_EXTRACT(metadata, '$.%s') = %s", ('currency', "USD"))
cur.execute("SELECT root_symbol FROM markets WHERE JSON_EXTRACT(metadata, '$.%s') = %s", ('tick_size', 0.25))

Can somebody explain to me why and how to fix it? Thank you!

1 Answer 1

1

You need to parameterize the whole field value for the JSON_EXTRACT():

cur.execute("""
   SELECT root_symbol 
   FROM markets 
   WHERE JSON_EXTRACT(metadata, %s) = %s""", ('$.currency', "USD"))

cur.execute("""
   SELECT root_symbol 
   FROM markets 
   WHERE JSON_EXTRACT(metadata, %s) = %s""", ('$.tick_size', 0.25))

Note the absence of quotes around the placeholders - the database driver would put it automatically if needed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.