Tips on how to Filter WHERE MySQL Queries in Python


First, you’ll need the mysql.connector. In case you are not sure of the way to get this setup, check with Tips on how to Set up MySQL Driver in Python.

Tips on how to 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 prospects WHERE deal with ='London Street'"
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Tips on how to 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 beneath instance, we are saying something that has the phrase highway in it someplace. Observe that it will exclude values that both begin or finish with highway.

import mysql.connector

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

mycursor = mydb.cursor()
sql = "SELECT * FROM prospects WHERE deal with LIKE '%highway%'"
mycursor.execute(sql)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Tips on how to Forestall SQL Injection in your WHERE clause

As a substitute of passing dynamic values immediately into your question, quite 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 prospects WHERE deal with = %s"
adr = ("Maple Drive", )

mycursor.execute(sql, adr)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Leave a Reply