This method prepare the given database
operation (query or command). The parameters
found in the tuple or dictionary params are
bound to the variables in the operation. Variables are specified
using %s markers or named markers %(name)s.
For example, insert information about a new employee and selecting again the data of this person:
insert = (
"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, data)
select = "SELECT * FROM employees WHERE emp_no = %(emp_no)s"
cursor.execute(select, { 'emp_no': 2 })Note that the data is converted from Python object to something MySQL understand. In the preceding example, the datetime.date() instance is converted to '2012-03-23'.
When multi is set to True,
execute() is able to execute multiple
statements. It returns an iterator which makes it possible to go
through all results for each statement. Note that using
parameters is not working well in this case, and it is usually a
good idea to execute each statement on its own.
In the following example we select and insert data in one operation and display the result:
operation = 'SELECT 1; INSERT INTO t1 VALUES (); SELECT 2'
for result in cursor.execute(operation):
if result.with_rows:
print("Statement '{}' has following rows:".format(
result.statement))
print(result.fetchall())
else:
print("Affected row(s) by query '{}' was {}".format(
result.statement, result.rowcount))If the connection was configured to fetch warnings, warnings generated by the operation are available through the MySQLCursor.fetchwarnings() method.
Returns an iterator when multi is
True.

User Comments
If you pass only one value to the query with a command looking like
mycursor.execute(query, value)
, you will get a ProgrammingError.
The right syntax will be
mycursor.execute(query, (value, ))
Add your own comment.