python-mysqlHow can I use Python to query a MySQL database with parameters?
To query a MySQL database with parameters using Python, you can use the MySQL Connector/Python
library. This library provides an API for accessing and manipulating databases from Python.
Below is an example of how to use MySQL Connector/Python
to query a MySQL database with parameters:
import mysql.connector
# Connect to MySQL database
mydb = mysql.connector.connect(
host="localhost",
user="user",
passwd="password",
database="mydatabase"
)
# Create a cursor object
mycursor = mydb.cursor()
# Define the query
sql = "SELECT * FROM customers WHERE address = %s"
# Define the parameters
params = ("Valley 345", )
# Execute the query
mycursor.execute(sql, params)
# Fetch the results
myresult = mycursor.fetchall()
# Print the results
print(myresult)
Output example
[('Peter', 'Lowstreet 4', 'Valley 345'),
('Amy', 'Apple st 652', 'Valley 345')]
This code does the following:
- Imports the
mysql.connector
library, which provides an API for accessing and manipulating databases from Python. - Connects to a MySQL database.
- Creates a cursor object to execute the query.
- Defines the query and the parameters.
- Executes the query with the parameters.
- Fetches the results.
- Prints the results.
Helpful links
More of Python Mysql
- How can I use Python to retrieve data from MySQL?
- How do I use Python to authenticate MySQL on Windows?
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I host a MySQL database using Python?
- How do I access MySQL using Python?
- How can I connect Python to a MySQL database using an Xserver?
- How do I connect Python with MySQL using XAMPP?
- How can I use the Python MySQL API to interact with a MySQL database?
See more codes...