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 can I access MySQL using Python?
- How can I connect to MySQL using Python?
- How can I use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I access MySQL using Python?
- How do I connect Python with MySQL using XAMPP?
- How do I use Python to authenticate MySQL on Windows?
- How can I create a web application using Python and MySQL?
- How can I use Python Kivy with MySQL?
See more codes...