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 do I access MySQL using Python?
- How can I use Python to interact with a MySQL database using YAML?
- How can I use Python and MySQL to create a login system?
- How can I connect Python to a MySQL database?
- How do I download MySQL-Python 1.2.5 zip file?
- How do I connect to a MySQL database using Python?
- How can I connect Python to a MySQL database using an Xserver?
- How can I connect Python and MySQL?
- How do I connect Python with MySQL using XAMPP?
- How do I connect Python to a MySQL database using Visual Studio Code?
See more codes...