What is the equivalent of psycopg curs.mogrify on mysql?
Asked Answered
J

2

5

What would be the equivalent of psycopg's cur.mogrify on mysql?

From: http://initd.org/psycopg/docs/cursor.html

mogrify(operation[, parameters]) Return a query string after arguments binding. The string returned is exactly the one that would be sent to the database running the execute() method or similar.

>cur.mogrify("INSERT INTO test (num, data) VALUES (%s, %s)", (42, 'bar'))
>"INSERT INTO test (num, data) VALUES (42, E'bar')"

DB API extension The mogrify() method is a Psycopg extension to the DB API 2.0.

Thanks in advance.

Jackshaft answered 15/1, 2014 at 12:36 Comment(0)
H
3

MySQL doesn't have anything built in that returns a query string like this. If you want to perform a query with variables substituted in, you use PREPARE and EXECUTE:

PREPARE stmt AS "INSERT INTO test(num, data) VALUES (?, ?)";
EXECUTE stmt USING 42, 'bar';
Horntail answered 15/1, 2014 at 12:42 Comment(0)
B
4

As per this example, you can see the results of the "mogrify" after the statement has been executed.

import MySQLdb

conn = MySQLdb.connect()
cursor = conn.cursor()

cursor.execute('SELECT %s, %s', ('bar', 1))
print cursor._executed

Which will print

SELECT 'bar', 1

Moreover, you don't need to use mogrify before execution

query = cursor.mogrify('SELECT %s, %s', ('bar', 1))
cursor.execute(query)

You can simply do the following

cursor.execute('SELECT %s, %s', ('bar', 1))

This will work across all DBs that use the Python DB API

Babbling answered 19/10, 2017 at 1:36 Comment(0)
H
3

MySQL doesn't have anything built in that returns a query string like this. If you want to perform a query with variables substituted in, you use PREPARE and EXECUTE:

PREPARE stmt AS "INSERT INTO test(num, data) VALUES (?, ?)";
EXECUTE stmt USING 42, 'bar';
Horntail answered 15/1, 2014 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.