INTERFACING PYTHON WITH MYSQL
Objective:
To write programs to connect python with mysql using database connectivity
and perform following operations on “EMPLOYEE” table in “BANK” database:
1. To display the names of all male staffs in employee table.
import mysql.connector as ms
mydb = ms.connect(host = “localhost”, user = “root”, passwd = “admin”, database =
“bank”)
if mydb.is_connected():
print(“Connection successful”)
mycursor = mydb.cursor()
sq = “select ename from employee where gender = ‘{ }’ “ . format(‘M’)
mycursor.execute(sq)
data = cursor.fetchall()
for row in data:
print(row)
mydb.close()
2. To insert new data into employee table:
import mysql.connector as ms
mydb = ms.connect(host = “localhost”, user = “root”, passwd = “admin”, database =
“bank”)
if mydb.is_connected():
print(“Connection successful”)
mycursor = mydb.cursor()
sq = “insert into employee values ({ }, ‘{ }’, ‘{ }’, ‘{ }’, ‘{ }’, ‘{ } ‘, { })” . format(1234,
‘Riya’ , ‘IT’, ‘Delhi’, ‘F’, ‘1996-10-12’, 30000.00)
mycursor.execute(sq)
mydb.commit()
mydb.close()
3. To update the salary of all employees of accounts department by incrementing
salary by 5000.
import mysql.connector as ms
mydb = ms.connect(host = “localhost”, user = “root”, passwd = “admin”, database =
“bank”)
if mydb.is_connected():
print(“Connection successful”)
mycursor = mydb.cursor()
sq = “update employee set salary = salary + {} where dept = ‘{ }’ . format(5000, ‘IT)
mycursor.execute(sq)
mydb.commit()
mydb.close()
4. To delete the records of all employees whose salary is less than 20000.
import mysql.connector as ms
mydb = ms.connect(host = “localhost”, user = “root”, passwd = “admin”, database =
“bank”)
if mydb.is_connected():
print(“Connection successful”)
mycursor = mydb.cursor()
sq = “delete from employee where salary < 20000.00”
mycursor.execute(sq)
mydb.commit()
mydb.close()