Select Query with where clause
Example
import mysql.connector
from mysql.connector import errorcode
try:
# Connecting with MySql
con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
# Using cursor() method to create cursor object
cursor = con.cursor()
# SQL query with where clause to fetch data.
sql_query = (
"SELECT * FROM EMPLOYEE where EMP_ID='E20021'"
)
# Executing query
cursor.execute(sql_query)
# Fetch all records
rows = cursor.fetchall()
print(rows)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Your user name or password is incorrect")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
con.close()
Example: Parametrized where clause
It prevents sql injection
import mysql.connector
from mysql.connector import errorcode
try:
# Connecting with MySql
con = mysql.connector.connect(user='root', password='mysql', host='127.0.0.1', database='company')
# Using cursor() method to create cursor object
cursor = con.cursor()
# SQL query with where clause to fetch data.
sql_query = (
"SELECT * FROM EMPLOYEE where EMP_ID=%s"
)
EMP_ID = ('E20021',)
# Executing query
cursor.execute(sql_query,EMP_ID)
# Fetch all records
rows = cursor.fetchall()
print(rows)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Your user name or password is incorrect")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
con.close()
Conclusion
Well, in this topic, we have learnt to use where clause in MySQL query. The where clause is used to fetch the data from the table based on some condition.
In our next topic, we will learn order by in table inside this database. Till then keep learning and practice.