How you can Filter WHERE MySQL Queries in Python


First, you will have the mysql.connector. If you’re not sure of tips on how to get this setup, consult with How you can Set up MySQL Driver in Python.

How you can Choose from MySQL with a Filter in Python

You merely specify the WHERE clause in your SQL assertion as follows:

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  consumer = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()
sql = "SELECT * FROM clients WHERE handle ='London Street'"
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

How you can Choose and Filter Wildcard Characters in Python

To filter wildcard characters, you mix the WHEREand LIKE key phrases, and place the % image the place the wildcards would happen.

Within the under instance, we are saying something that has the phrase street in it someplace. Observe that this can exclude values that both begin or finish with street.

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  consumer = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()
sql = "SELECT * FROM clients WHERE handle LIKE '%street%'"
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

How you can Stop SQL Injection in your WHERE clause

As an alternative of passing dynamic values straight into your question, moderately go them because the second argument to the execute command, as a set.

import mysql.connector

mydb = mysql.connector.join(
  host = "localhost",
  consumer = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

mycursor = mydb.cursor()

sql = "SELECT * FROM clients WHERE handle = %s"
adr = ("Maple Drive", )

mycursor.execute(sql, adr)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Leave a Reply