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%sis 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 do I download MySQL-Python 1.2.5 zip file?
- How do I connect Python with MySQL using XAMPP?
- How do I set up a secure SSL connection between Python and MySQL?
- How can I convert a MySQL query result to a Python dictionary?
- How can I connect to MySQL using Python?
- How to compile a MySQL-Python application for x86_64-Linux-GNU-GCC?
- How do I use a WHERE query in Python and MySQL?
- How do I set up a remote connection to a MySQL database using Python?
- How do I insert NULL values into a MySQL table using Python?
- How can I access MySQL using Python?
See more codes...