How to Fetch One Record From Database in Python

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

Program 1

# Program to search one record (based on PK)
import MySQLdb
try:
    con=MySQLdb.connect(host='localhost',user='root',password='root',database='college')   
    #print("Data base connected")
    empid=int(input("Enter employee id for search: "))
    sql="select * from employee where eid={}"
    sql=sql.format(empid)
    cur=con.cursor()
    cur.execute(sql)
    result=cur.fetchone()
    if(result):
        print("------------------------------------------")
        print("Emp Id\tName\tDepartment\tSalary\tGender\tCity")
        print("------------------------------------------")
        print("%d\t%s\t%s\t%d\t%s\t%s"%(result[0],result[1],result[2],result[3],result[4],result[5]))
    else:
        print("******* No Record Found*********")    
except Exception as obj:
    print(obj)

Program 2

# Program to search record acording to Name
import MySQLdb
try:
    con=MySQLdb.connect(host='localhost',user='root',password='root',database='college')   
    #print("Data base connected")
    empname=input("Enter employee name for search: ")
    sql="select * from employee where ename='{}'"
    sql=sql.format(empname)
    cur=con.cursor()
    cur.execute(sql)
    result=cur.fetchall()
    flag=True
    print("------------------------------------------")
    print("Emp Id\tName\tDepartment\tSalary\tGender\tCity")
    for row in result:
        flag=False
        print("%d\t%s\t%s\t%d\t%s\t%s"%(row[0],row[1],row[2],row[3],row[4],row[5]))
    print("------------------------------------------")    
    if(flag==True):
        print("******* No Record Found*********")    
except Exception as obj:
    print(obj)

Program 3

# Program to search record acording to Department
import MySQLdb
try:
    con=MySQLdb.connect(host='localhost',user='root',password='root',database='college')   
    #print("Data base connected")
    empdept=input("Enter employee department for search: ")
    sql="select * from employee where edept='{}'"
    sql=sql.format(empdept)
    cur=con.cursor()
    cur.execute(sql)
    result=cur.fetchall()
    flag=True
    print("------------------------------------------")
    print("Emp Id\tName\tDepartment\tSalary\tGender\tCity")
    for row in result:
        flag=False
        print("%d\t%s\t%s\t%d\t%s\t%s"%(row[0],row[1],row[2],row[3],row[4],row[5]))
    print("------------------------------------------")    
    if(flag==True):
        print("******* No Record Found*********")    
except Exception as obj:
    print(obj)

 

Did you like this article? If Yes, please give DataFlair 5 Stars on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply