python-mysqlHow do I use MySQL bind variables in Python?
MySQL bind variables in Python are used to pass data from a Python application to a MySQL database. The data is passed in the form of a tuple, and the bind variables are used to refer to the data in the tuple.
For example, the following code block creates a connection to a MySQL database, creates a cursor, and then uses the cursor to execute a query with a bind variable:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"
val = ("John", "Highway 21")
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "record inserted.")
This will output: 1 record inserted.
The code is composed of the following parts:
import mysql.connectorimports the MySQL Connector/Python module.mydb = mysql.connector.connect(...)creates a connection to the MySQL database.mycursor = mydb.cursor()creates a cursor object.sql = "INSERT INTO customers (name, address) VALUES (%s, %s)"creates a string containing a SQL query with two bind variables.val = ("John", "Highway 21")creates a tuple containing the data to be inserted.mycursor.execute(sql, val)executes the query with the bind variables.mydb.commit()commits the changes to the database.print(mycursor.rowcount, "record inserted.")prints the number of records inserted.
For more information, see the MySQL Connector/Python documentation.
More of Python Mysql
- How do I connect Python with MySQL using XAMPP?
- How can I connect Python to a MySQL database?
- How do Python and MySQL compare to MariaDB?
- How do I connect Python to a MySQL database using Visual Studio Code?
- How do I access MySQL using Python?
- How can I use Python to interact with a MySQL database using YAML?
- How can I connect to MySQL using Python?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I connect to XAMPP MySQL using Python?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
See more codes...