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 do I connect to XAMPP MySQL using Python?
- How can I use a while loop in Python to interact with a MySQL database?
- How do Python MySQL and SQLite compare in terms of performance and scalability?
- How can I set a timeout for a MySQL connection in Python?
- How do I create a Python script to back up my MySQL database?
- How do I use a SELECT statement in Python to query a MySQL database?
- How do I use Python to show the MySQL processlist?
- How can I use Python to retrieve data from MySQL?
See more codes...