python-mysqlHow do I use Python to query MySQL with multiple conditions?
Using Python to query MySQL with multiple conditions is easy and straightforward. The following example code shows how to do this:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
passwd="yourpassword",
database="mydatabase"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM customers WHERE address = %s AND name = %s"
adr = ("Park Lane 38", "John")
mycursor.execute(sql, adr)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
The output of the above code is:
('John', 'Park Lane 38')
The code consists of the following parts:
-
import mysql.connector
: This is used to import the MySQL Connector Python module in order to connect to a MySQL database. -
mydb = mysql.connector.connect()
: This line of code is used to create a connection to the MySQL database. -
mycursor = mydb.cursor()
: This line of code is used to create a cursor object which will be used to execute the SQL query. -
sql = "SELECT * FROM customers WHERE address = %s AND name = %s"
: This line of code is used to define the SQL query. The%s
is used as a placeholder for the values which will be passed as parameters to the query. -
adr = ("Park Lane 38", "John")
: This line of code is used to define the values which will be passed as parameters to the SQL query. -
mycursor.execute(sql, adr)
: This line of code is used to execute the SQL query with the parameters specified. -
myresult = mycursor.fetchall()
: This line of code is used to fetch all the rows from the result set of the query. -
for x in myresult: print(x)
: This line of code is used to iterate through the result set and print out the values.
For more information on using Python to query MySQL with multiple conditions, please refer to the following links:
More of Python Mysql
- How can I connect Python to a MySQL database?
- How can I use Python to interact with a MySQL database using YAML?
- ¿Cómo conectar Python a MySQL usando ejemplos?
- How do I use Python to authenticate MySQL on Windows?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How do I use a cursor to interact with a MySQL database in Python?
- How do I use Python to update multiple columns in a MySQL database?
- How do I use a Python variable in a MySQL query?
- How do I connect Python to a MySQL database using Visual Studio Code?
See more codes...