2

What are different ways to reference a Python variable into MySQL statement?

I know you can reference like this:

var = "String"

cursor.execute("select * from table where column1 = %s") % (var)

I saw somebody mention to use ?. What are other ways to do it?

1
  • 1
    Your statement above is totally incorrect. Commented Jan 20, 2020 at 12:47

1 Answer 1

4

You can do this by passing parameters:

cursor = connection.cursor(prepared=True)
sql_insert_query = """ INSERT INTO Employee
                       (id, Name, Joining_date, salary) VALUES (%s,%s,%s,%s)"""

insert_tuple_1 = (1, "Json", "2019-03-23", 9000)
cursor.execute(sql_insert_query, insert_tuple_1)
connection.commit()

Example taken from here

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.