Database Connectivity Programs
Database Connectivity Programs
Q. Program to connect with database and store record of employee and display
records.
Ans.
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :1
Enter Employee Number :1
Enter Name :AMIT
Enter Department :SALES
Enter Salary :9000
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :1
Enter Employee Number :2
Enter Name :NITIN
Enter Department :IT
Enter Salary :80000
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :2
1 AMIT SALES 9000
2 NITIN IT 80000
1.ADD RECORD
2.DISPLAY RECORD
0.EXIT
Enter Choice :0
## Bye!! ##
Program 18
Q. Program to connect with database and search employee number in table
employee and display record, if empno not found display appropriate message.
Ans.
import mysql.connector as mycon
con=mycon.connect(host='localhost',user='root',password='mysql',database='comp
any')
cur = con.cursor( )
ans='y'
while ans.lower( )=='y':
eno = int(input("ENTER EMPNO TO SEARCH :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0],row[1],row[2],row[3])
ans=input("SEARCH MORE (Y/N) :")
Output:
Ans.
import mysql.connector as mycon
con =
mycon.connect(host='localhost',user='root',password='mysql',database="company"
)
cur = con.cursor( )
ans='y'
while ans.lower()=='y':
eno =int(input("ENTER EMPNO TO UPDATE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall()
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0],row[1],row[2],row[3])
choice=input("\n## ARE YOUR SURE TO UPDATE ? (Y) :")
if choice.lower()=='y':
print("== YOU CAN UPDATE ONLY DEPT AND SALARY ==")
print("== FOR EMPNO AND NAME CONTACT ADMIN ==")
d = input("ENTER NEW DEPARTMENT,(LEAVE BLANK IF NOT
WANT TO CHANGE )")
s = int(input("ENTER NEW SALARY,(LEAVE BLANK IF NOT
WANT TO CHANGE ) "))
query="update employee set dept='{}',salary={} where
empno={}".format(d,s,eno)
cur.execute(query)
con.commit()
print("## RECORD UPDATED ## ")
ans=input("UPDATE MORE (Y) :")
Output:
Ans.
import mysql.connector as mycon
con =
mycon.connect(host='localhost',user='root',password='mysql',database='company')
cur = con.cursor( )
ans='y'
while ans.lower( )=='y':
eno = int(input("ENTER EMPNO TO DELETE :"))
query="select * from employee where empno={}".format(eno)
cur.execute(query)
result = cur.fetchall( )
if cur.rowcount==0:
print("Sorry! Empno not found ")
else:
for row in result:
print(row[0],row[1],row[2],row[3])
choice=input("\n## ARE YOUR SURE TO DELETE ? (Y) :")
if choice.lower( )=='y':
query="delete from employee where empno={}".format(eno)
cur.execute(query)
con.commit()
print("=== RECORD DELETED SUCCESSFULLY! ===")
ans=input("DELETE MORE ? (Y) :")
Output: