#Writ e a program to connect mysql database with python.
import mysql.connector as sql
db = sql.connect(host="localhost", user="root", passwd="12345", database="test")
if db.is_connected():
print("Successfully connection")
else:
print("Error")
#Writ e a program to create table in mysql database using python.
query="CREATE TABLE IF NOT EXISTS student(sid integer PRIMARY KEY,\
name varchar(30) NOT NULL,\
std integer DEFAULT 11,\
contact_no char(13) UNIQUE,\
age integer CHECK(age >= 15),\
gender char(1))"
c=db.cursor()
c.execute(query)
db.commit()
print("Table Created Successfully")
c.close()
#Writ e a program to insert record in table using python.
s_id=int(input("Enter your ID: "))
s_name=input("Enter your Name: ")
std=int(input("Enter your Standard: "))
contact_no=input("Enter your Contact No: ")
age=int(input("Enter your Age: "))
gender=input("Enter your Gender: ")
c=db.cursor()
query="INSERT INTO student(sid,name,std,contact_no,age,gender) VALUES ({},'{}',{},{},{},'{}')".format(s_id,
s_name,std,contact_no,age,gender)
c.execute(query)
db.commit()
print("Record Added To Table Successfully")
c.close()
#Writ e a program to display record in table using python.
c=db.cursor()
c.execute("SELECT * FROM student")
data=c.fetchall()
cnt=c.rowcount
print("Total rows: ",cnt)
for row in data :
print(row)
c.close()
#Writ e a program to update record in table using python.
s_id=int(input("Enter ID whose record you want to modify: "))
s_name=input("Enter your Name: ")
std=int(input("Enter your Standard: "))
contact_no=input("Enter your Contact No: ")
age=int(input("Enter your Age: "))
gender=input("Enter your Gender: ")
c=db.cursor()
query=" UPDATE student SET name='{}',std={},contact_no={},age={},gender='{}' WHERE
sid={}".format(s_name,std,contact_no,age,gender,s_id)
c.execute(query)
db.commit()
print("Record Modified Successfully.")
c.close()
#Writ e a program to search record in table using python.
n=int(input("Enter Student ID to search :"))
c=db.cursor()
c.execute("SELECT * FROM student WHERE sid=%i"%(n))
data=c.fetchall()
cnt=c.rowcount
if cnt==0:
print("Record not found.")
else:
print("Total rows: ",cnt)
for row in data:
print(row)
c.close()
#Writ e a program to delete record in table using python.
s_id=int(input("Enter Student ID to be deleted :"))
c=db.cursor()
query="DELETE FROM student WHERE sid= {}".format(s_id)
c.execute(query)
x=c.rowcount
if x>0:
print("Records found ",x)
db.commit()
print("Record Deleted Successfully.")
else:
print("No Such record Found")
c.close()
db.close()