Python MySQL cursor.execute() Explained with Examples

MySQL cursor.execute() method is used to execute SQL queries against a MySQL database through a cursor object.

Syntax

cursor.execute(sql_query, params=None)

Parameters

sql_query (str): The SQL query to be executed.

params (tuple or dict): Optional parameters to be used in the query placeholders.

Example

You can use cursor.execute() to insert a row into a table.

import mysql.connector

# Establish connection to MySQL server
connection = mysql.connector.connect(
    host="localhost",
    user="root",
    password="password",
    database="mydatabase"
)

cursor = connection.cursor()

# Execute an SQL query
query = "INSERT INTO users (name, email) VALUES (%s, %s)"
values = ("Alice", "alice@example.com")

cursor.execute(query, values)

# Commit the transaction
connection.commit()

connection.close()

In this example, you should use connection.commit() to commit any changes to the database after executing the query.
Finally, connection.close() is used to close a mysql connection.