Python MySql Where Clause
We can restrict the result produced by the select statement by using the where clause. This will extract only those columns which satisfy the where condition.
MySql Where Clause
In this example, we will query mysql database with the where clause to get results which are satisfy the where clause.
Where clause example 1:Copied
import mysql.connector
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "gkindex",database = "PythonDB")
cur = myconn.cursor()
try:
cur.execute("select name, id, salary from Employee where name like 'J--'")
result = cur.fetchall()
print("Name id Salary");
for row in result:
print("--s --d --d"--(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()
Where clause example 2:
Copied
import mysql.connector
myconn = mysql.connector.connect(host = "localhost", user = "root",password = "gkindex",database = "PythonDB")
cur = myconn.cursor()
try:
cur.execute("select name, id, salary from Employee where id in (101,102,103)")
result = cur.fetchall()
print("Name id Salary");
for row in result:
print("--s\t--d\t--d"--(row[0],row[1],row[2]))
except:
myconn.rollback()
myconn.close()