Wednesday, May 17, 2023
HomeSoftware EngineeringEasy methods to Filter WHERE MySQL Queries in Python

Easy methods to Filter WHERE MySQL Queries in Python


First, you have to the mysql.connector. In case you are uncertain of how one can get this setup, confer with Easy methods to Set up MySQL Driver in Python.

Easy methods 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",
  person = "username",
  password = "YoUrPaSsWoRd",
  database = "your_database"
)

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

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Easy methods 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 street in it someplace. Be aware that it will exclude values that both begin or finish with street.

import mysql.connector

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

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

myresult = mycursor.fetchall()

for x in myresult:
  print(x)

Easy methods to Forestall SQL Injection in your WHERE clause

As a substitute of passing dynamic values instantly into your question, slightly go them because the second argument to the execute command, as a set.

import mysql.connector

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

mycursor = mydb.cursor()

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

mycursor.execute(sql, adr)

myresult = mycursor.fetchall()

for x in myresult:
  print(x)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments