3

I am learning to use MySQL Connector/Python. In most of the tutorials, I see they use the %s placeholder inside VALUES clause for inserting data in a table. Then, on the next line, the values are stored in a tuple. And then, they execute the command.

sql = "INSERT INTO table (col1, col2) VALUES (%s, %s)"
val = ("Foo", "Bar")
cursor.execute(sql, val)

So what does this %s mean? Is it the same as the one used in C? I saw people using this in C. I am just curious. Please do give any reference link, if any. Thanks.

Shounak Das
  • 515
  • 4
  • 19
  • 1
    %s ia a placeholder for a string, I suggest this: https://stackoverflow.com/questions/4288973/whats-the-difference-between-s-and-d-in-python-string-formatting – JLeno46 Nov 22 '20 at 11:39

1 Answers1

2

It tells the string that the value will be converted to a string and replace the placeholder at that position.

But the connector also supports prepared statements.

cursor = connection.cursor(prepared=True)
sql_insert_query = """ INSERT INTO customers (name, address) VALUES (%s, %s)"""

insert_tuple_1 = ("Json", "BAker street")
insert_tuple_2 = ("Emma", "Avenue des Champs-Élysées")

cursor.execute(sql_insert_query, insert_tuple_1)
cursor.execute(sql_insert_query, insert_tuple_2)
connection.commit()
Shounak Das
  • 515
  • 4
  • 19
nbk
  • 45,398
  • 8
  • 30
  • 47