Home >>Python Tutorial >Python MySQL Where

Python MySQL Where

Select With a Filter

This is the python mysql where module of our entire Python MySQL tutorial. And if you are selecting records from a particular table and then, if you wish to filter those results a bit then you can do that in this programming language. To accomplish that task you need to use the “WHERE” statement. For example, if you wish to select all the particular records from a table with the address of ‘Park Lane 38’ then  
import mysql.connector



mydb = mysql.connector.connect (

  host=“localhost” ,

  user=“yourusername” ,

  passwd=“yourpassword” ,

  database=“mydatabase” ,

)



mycursor = mydb.cursor ( )



sql = “SELECT * FROM customer WHERE address = ‘Park Lane 38’ ”



mycursor.execute ( sql )

myresult = mycursor.fetchall ( )



for x in myresult :

  print ( x )
 

The Wildcard Characters

The wildcard characters concept is a rather interest concept. And it basically dictates that you as a developer who is using this programming language have the power to select all the records that start, end, or even include any particular kind of letter or phrase. If you wish to represent any particular wildcard character then you can do that by using % as the character. For example, if you wish to select all possible records that contain the word ‘way’ then
import mysql.connector



mydb = mysql.connector.connect (

  host=“localhost” ,

  user=“yourusername” ,

  passwd=“yourpassword” ,

  database=“mydatabase” ,

)



mycursor = mydb.cursor ( )



sql = “SELECT * FROM customer WHERE address LIKE ‘%way%’  ”



mycursor.execute ( sql )

myresult = mycursor.fetchall ( )



for x in myresult :

  print ( x )
Another interesting concept is that of the mysql order by desc limit.  

To Prevent SQL Injection

It is recommended that whenever you observe a particular query value that is being provided by the user then you should always escape that value. This particular step is taken so that you can succeed in preventing any kind of SQL injection. The SQL injection is nothing but a common hacking method. This is different from the concept of mysql order by desc limit. This hacking method is performed to misuse or to destroy the data that is present in your database. In the mysql.connector module there are quite a few methods that you can use to escape the value that is being returned. The first is the placeholder ( % ) method.

For example

import mysql.connector


mydb = mysql.connector.connect (

  host=“localhost” ,

  user=“yourusername” ,

  passwd=“yourpassword” ,

  database=“mydatabase” ,

)



mycursor = mydb.cursor ( )



sql = “SELECT * FROM customer WHERE address = %s ”

adr = ( “Yellow Garden 2” )



mycursor.execute ( sql, adr )



myresult = mycursor.fetchall ( )



for x in myresult :

  print ( x )
With this, we finish the python mysql where part of our entire Python MySQL tutorial.

No Sidebar ads