Here is another way to do this. This is documented on the official MySQL site. https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-execute.html
In the spirit, he uses the same @Trey Stout answer mechanics. Nevertheless, I believe that it is more beautiful and more readable.
insert_stmt = ( "INSERT INTO employees (emp_no, first_name, last_name, hire_date) " "VALUES (%s, %s, %s, %s)" ) data = (2, 'Jane', 'Doe', datetime.date(2012, 3, 23)) cursor.execute(insert_stmt, data)
And to better illustrate any need for variables:
NB: note that the escape is being done.
employee_id = 2 first_name = "Jane" last_name = "Doe" insert_stmt = ( "INSERT INTO employees (emp_no, first_name, last_name, hire_date) " "VALUES (%s, %s, %s, %s)" ) data = (employee_id, conn.escape_string(first_name), conn.escape_string(last_name), datetime.date(2012, 3, 23)) cursor.execute(insert_stmt, data)
Djidiouf Feb 01 '18 at 0:04 2018-02-01 00:04
source share