How to Execute Parameterized Query in Python PDBC

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

Program 1

# Program for PDBC
import MySQLdb
try:
    con=MySQLdb.connect(host='localhost',user='root',password='root',database='DataFlair')   
    print("Data Base connected")
    eno=int(input("Enter Employee No:"))
    name=input("Enter Employee Name:")
    mobile=int(input("Enter Mobile No:"))
    age=int(input("Enter Employee age:"))
    sql="insert into employee values(%d,'%s',%d,%d)"
    values=(eno,name,mobile,age)
    cur=con.cursor()
    n=cur.execute()
    con.commit()
    print("Record inserted: ",n)
except Exception as obj:
    print(obj)    
finally:
    con.close()

Program 2

# Program to fetch data using parameterized query
import MySQLdb
try:
    con=MySQLdb.connect(host='localhost',user='root',password='root',database='DataFlair')   
    print("Data Base connected")
    eno=int(input("Enter Employee no for search:"))
    sql="select * from employee where eid=%d"
    cur=con.cursor()
    cur.execute(sql% eno)
    result=cur.fetchone()
    if(result):
        print("%d %s %d %d"%(result[0],result[1],result[2],result[3]) )
    else:
        print("No Record found")
    
except Exception as obj:
    print(obj)    
finally:
    con.close()

 

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback 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