0% found this document useful (0 votes)
4 views4 pages

SOLUTIONS

The document provides a series of programming tasks related to interfacing Python with MySQL, including establishing connections, executing SQL commands, and handling data. It also includes Python programming exercises for file handling, stack implementation, and CSV file operations. Each section outlines specific statements to be completed or SQL commands to be written, along with solutions and explanations.

Uploaded by

srm599298
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views4 pages

SOLUTIONS

The document provides a series of programming tasks related to interfacing Python with MySQL, including establishing connections, executing SQL commands, and handling data. It also includes Python programming exercises for file handling, stack implementation, and CSV file operations. Each section outlines specific statements to be completed or SQL commands to be written, along with solutions and explanations.

Uploaded by

srm599298
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 4

Interface Python with MYSQL Solutions

1. Write the following missing statements to x=_ms.connect(__________)


complete Python and MYSQL connectivity. #statement 2
import _________________as ms if x.is_connected( ):
#statement 1 cur =x.cursor( )
x=ms.connect(host="localhost",user="r
oot",passwd="root",database="school2") cur.execute("_______________________")
if x.is_connected(): #statement 3
cur=x.cursor() x.commit()
cur.execute("select * from transactions")
cur.execute("_____________________
data=cur.fetchall( )
_______”) #statement 2
for i in data:
s_id=int(input("Enter rollno:"))
print(i)
sname=input("Enter name:")
___________
mark=int(input("Enter mark:"))
#statement 4
cur.execute("__________values({},'{}', Statement 1: Write the module required for connecting
{})".format(s_id,sname,mark) Python and MYSql
#statement 3 Statement 2: Write the parameters that is required for
print("data insert successfully") establishing connection where database name is
x.__________ #statement 4 “school2”
print("contents of table are:") Statement 3: Write the sql command to remove records
cur.execute("SELECT * FROM stud1") from table ”transactions” whose
data=cur.fetchall() Tno is ‘T002’
for i in data: Statement 4: Write the statement to disconnect the
print(i) connection
x.close()
Statement 1: Write the module required for Ans:
connecting Python and MYSql Statement 1: mysql.connector
Statement 2: Write the sql command to create the table Statement2:
“stud” host=”localhost”,user=”root”,passwd=”root”,database=
Statement 3: Write the sql command to add the given ”school2”
record in the table “stud” Statement3: delete from transactions where tno=”T002”
Statement 4: Write the sql command to save the Statement4: x.close( )
changes permanently 3. Write the following missing statements to
Ans: complete Python and MYSQL connectivity.
Statement1: mysql.connector
Statement2: create table stud(sid int(10) not null
primary key, sname varchar(25),mark integer(5)) import mysql.connector as ms
Statement3: insert into stud x=___________
Statement4:commit( ) (host="localhost",user="root",passwd="roo
2. Write the following missing statements to t",database="school2")
complete Python and MYSQL connectivity. #statement 1
if x.is_connected( ):
cur =x.cursor( )
import ________________as ms
#statement 1
cur.execute("_______________________")
# statement 2
x.commit() Statement 1: : Write the module required for
connecting Python and MYSql
cur.execute(“________________________ Statement2: Write the statement to check the
___”) # statement 3 connection establishment.
data=cur._____________ # statement 4 Statement 3: Write the sql command to display the
for i in data: records of employee whose salary is greater than 30000
from emp table.
print(i)
Statement 4: Write the sql command to display the
x.close( )
records of employee whose salary is greater than 30000
Statement 1: Write the method that establishes and gender is male from “emp” table.
connection between Python and MYSql Ans:
Statement 2: Write the sql command to increase the Statement1: mysql.connector as mycur
salary of an employee by 5% whose Statement2: mycur.is_connected()
Statement3: Select * from emp where salary >30000
itcode is 12 of table “salesperson”
Statement4: Select * from emp where salary >30000 and
Statement 3: Write the sql command to retrieve all the
gender=”M”
records of table “salesperson” 5. Write the following missing statements to
Statement 4: Write the method to retrieve all the
complete Python and MYSQL connectivity
records from the result set.
import ________________as ms
Ans:
#statement 1
Statement1: ms.connect( )
mycur=ms.connect(host='localhost',user='r
Statement2: update salesperson set
salary=salary*0.5+salary where itcode=12 oot',passwd='root',database='school2')
Statement3:select * from salesperson; if mycur.is_connected():
Statement4: fetchall( ) print("success")
4. Write the following missing statements to cur=mycur.__________ #
complete Python and MYSQL connectivity. statement 2
cur.execute(_____________)
import ________________ # statement 1 #statement 3
mycur=ms.connect(host='localhost',user='root', mycur.commit()
passwd='root',database='school2') print("new column added")
cur.execute(__________)
if __________________: #statement 2 #statement 4
print("success") mycur.close()
cur=mycur.cursor()
Statement 1: Write the module that is required to create
the connectivity between Python and MYSql
cur.execute(______________________) Statement 2: Write the method to create the cursor
#statement 3 object
Statement 3: Write the sql command to add a new
print("\n contents are:") column “DOB” in the existing table “emp”
data=cur.fetchall() Statement 4: Write the sql command to view the
for row in data: structure of the table “emp”.
ANS:
print(row)
Statement1: mysql.connector
Statement2: cursor()
cur.execute(_____________________________ Statement3: alter table emp add column dob date;
________) #statement 4 Statement4: desc emp;

print("\n contents are:")


data=cur.fetchall()
for row in data:

print(row)
mycur.close()
if choice==1:
view( )
elif choice==2:
fno=int(input("enter flight no:"))
fname=input("enter flight name:")
Python Programs Solutions fare=float(input ("enter fare:"))
1. Write a program that writes the content into the flight=[fno,fname,fare]
text file “myfile.txt” and count and display the push(stack,flight)
total number of uppercase and lowercase elif choice==3:
characters pop( )
Sol. else:
def write(): print("wrong choice")
fw=open("myfile.txt","w") break
L=["Twinkle Twinkle Little Star\n" 3. Write a program that writes the content into
"How I wonder what you are\n" the text file “myfile.txt” and count and display
"Up above the world sohigh\n" those lines that starts with ‘T’ or ‘t’.
"Like a diamond in the sky\n"
Sol.
"Twinkle Twinkle Little star\n"]
def write():
fw.writelines(L)
fw=open("myfile.txt","w")
fw.close()
L=["Twinkle Twinkle Little Star\n"
def count():
"How I wonder what you are\n"
fr=open("myfile.txt","r")
"Up above the world sohigh\n"
fc=fr.read()
"Like a diamond in the sky\n"
cu=0
"Twinkle Twinkle Little star\n"]
cl=0
fw.writelines(L)
for i in fc:
fw.close()
if i.isupper():
def count_lines():
cu+=1
fr=open("myfile.txt","r")
elif i.islower():
fc=fr.readlines()
cl+=1
ct=0
print("No. of uppercases:",cu)
for i in fc:
print("No. of lowercases:",cl)
if i[0]=="T" or i[0]=="t":
fr.close()
ct+=1
write( )
print(i)
count( )
print("Count of lines starting with T:",ct)
2.Write a program to implement stack using list data
fr.close()
structure( Push,Pop & View)
write()
Sol.
count_lines( )
stack=[ ]
4.Write a program to create a binary file “stud.dat”
def view ():
to write the content[rno,name,marks] and search for
for x in range(len(stack)-1,-1,-1):
the given rollno and display.
print(stack[x])
Sol.
def push(stk,item):
import pickle
stk.append(item)
def create_binfile():
def pop( ):
stu=dict()
if stack==[]:
stufile=open("stu.dat","wb")
print("stack is empty")
ans='y'
else:
while ans =='y':
item=stack.pop(-1)
rno=int(input("enter roll no:"))
print("delected item:",item)
name=input("enter name:")
print("stack operation")
marks=float(input("enter marks:"))
print("1.view")
stu["rollno"]=rno
print("2.push")
stu["name"]=name
print("3.pop")
stu["marks"]=marks
while True:
pickle.dump(stu,stufile)
choice=int (input("enter your choice:"))
ans=input("want more records?(y/n)")
stufile.close()

def search_binfile():
fin=open("stu.dat","rb")
stud=dict()
rno1=int(input("enter roll no to search"))
print("student details")
try:
while True:
stud=pickle.load(fin)
if stud["rollno"]==rno1:
print(stud)
else:
print("record not found")
except EOFError:
fin.close()
create_binfile()
search_binfile()

5.Write a program to create a csv file “sports.csv” to


write the content [sports, competition, price] in to
the file and read the same .
Sol.
import csv
fh=open("sports.csv","w",newline="")
swriter=csv.writer(fh)
swriter.writerow(["sports","competition","price"])
ans='y'
while ans=='y':
sports=input("enter sports name:")
comp=int(input("enter number of competiton:"))
prize=int(input("enter number of prize won:"))
srec=[sports,comp,prize]
swriter.writerow(srec)
ans=input("want more records?(y/n)..")
fh.close()
with open("sports.csv","r")as fin:
creader=csv.reader(fin)
print("sports performance")
for rec in creader:
print(rec)

You might also like