import mysql.connector
# Establish a connection to the database
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Create a cursor object to execute queries
cursor = db.cursor()
# Execute the query to select data with a filter
query = "SELECT * FROM tablename WHERE column1 = %s AND column2 > %s"
values = ("value1", 10)
cursor.execute(query, values)
# Fetch all rows returned by the query
rows = cursor.fetchall()
# Display the rows
for row in rows:
print(row)
# Close the database connection
db.close()
mysql.connector
` module. We then create a cursor object to execute queries.SELECT
` statement is used to select data from a table with a filter. In this example, we are selecting all columns from a table called `tablename
` where `column1
` has a value of `'value1
'` and `column2
` is greater than `10
`. You can replace these column names and table name with your own.%s
` placeholder to specify values for the filter conditions. The actual values are passed as a tuple to the `execute()
` method.fetchall()
` method is used to fetch all rows returned by the query. We then display the rows using a `for
` loop.close()
` method.