Google News
logo
Python Program to Select with a filter
Here's a Python program to select data from a table with a filter :
Program :
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()
In this program, we first establish a connection to the MySQL database using the `mysql.connector` module. We then create a cursor object to execute queries.

The `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.

We use the `%s` placeholder to specify values for the filter conditions. The actual values are passed as a tuple to the `execute()` method.

The `fetchall()` method is used to fetch all rows returned by the query. We then display the rows using a `for` loop.

Finally, we close the database connection using the `close()` method.