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.connector
imports 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 use Python and MySQL to generate a PDF?
- How can I connect Python to a MySQL database?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How do Python and MySQL compare to MariaDB?
- How do I use Python to update multiple columns in a MySQL database?
- How do I connect Python with MySQL using XAMPP?
- How can I connect to MySQL using Python?
- How do I use Python to authenticate MySQL on Windows?
- How can I convert a MySQL database to a SQLite database using Python?
See more codes...