COLDER
COLDER

Reputation: 29

how to insert variables into mysql query

hello i am new to python, i started learning how to work with mysql but the question arose - how to insert variables into mysql query?

I have code like this now:

table_name = "bot"
variable = 15

mySql_insert_query = """INSERT INTO %s (Id) 
                        VALUES
                        (%s) """    

I try to execute the code, but it gives an error: SyntaxError: EOF while scanning triple-quoted string literal attempt to call a nil value

How to write the code correctly? thanks

Upvotes: 0

Views: 868

Answers (2)

balderman
balderman

Reputation: 23825

Below is an example taken from here.

...
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)
...

In your case:

   cursor.execute("""INSERT INTO bot VALUES (%s)""", (15,))

Upvotes: 1

Jimmy Fraiture
Jimmy Fraiture

Reputation: 452

Just use :mySql_insert_query = "INSERT INTO" +table_name+"VALUES " + variable

Upvotes: -1

Related Questions