PySql Connectivity
PySql Connectivity
No.
Expt.
pogsam to
duplay data 4xom OL table in
mysQL
Loge
Stant
Lmpost sl connectox
my
Irtiate connectio to D4mysqloodule
dotabae hoct anc
C7edentials
ConnectC method od ctose Yaiable
mycen
Initialize ox the Connectlon and storge avaniahle
SOWS ed
stox tn vaniables
Shop
SouReE CaDE
lpostmysql connectag
mycon Chost = lbealhosE root
Sqltn Connect USen
Cmangch
database= "lsps s)
Con CwnsoxC)
my con
Teacher's
Signature
as sqltor lsps')
ZmpOrt mysql.connector user
= "localhost", =root*,
passwOrd = manager',database =
mycon = sqltor.connect
(host
cursor= nycon.cursor) ")
execute("Select* from student:
cursor.
datal = cursor.
fetchone )
ata2 = cursor.
fetchmany (3)
data3 = fetchall()
cursor.
('Datareceivedusing fetchone() commai: \n',datal)
print ")
using fetchmany () gommand:
print("Datareceived
for iin ata2:
(i)
print
("Data receivedusingetchall()
print command:' )
for iin data3:
(i)
print
cOunt= Cursor.rOWCOunt
("Iotal
print nunber of rowS = ",
retrieved count)
mycon.Close()
12
No.
Eypt.
10prairt
Lpatnt
Data 3eeeivec ing etochone C) corommand :n", data 1)
Data. xeclud uing fetch manyc) command: ")
pzint (i)
19Count =
con
Dut Dut
22,'
ceive d
42,Tarme',C
Data
Smith' Female Mathtmn ahci Decimal 3.90),
Teacher'sSignature
,Data receivedusingfetchone()
command:
2 (1, 'John',
'Doe',20, 'Male', 'Computer Scíence',
3 Data receivedusing fetchmany() command: Decimal('3.75'), datetime.date(2022, 1, 15))
(2,'Jame','Smith',
<(3,'Bob',
22, 'Female',
'Johnson', 21,'Male',
',
'Mathematics Decimal('3.90'), datet ime.date(2022,2, 20))
(4,'Alice', ',
'Williams 19,'femaleChemistry
? Data retrievedusing fetchall
',
'Physiçs, Decimal('3.60'),
Decimal('3.
datetime. d
34'),datetime.date
3
ate(2022, , 10))
(2022, 4,5))
(Command:
(5,'Charlie',
'Brown',23,'Male,'Engineering',
9 (6, 'Eve',
o (7,
'Davis',20,Female',
'Miller',22,
'Michael',
'
'Male',
,,
Biology'Decimal
'Business'
Decimal('3.95'),
('3.70'),
datetime
Decimal('3.85"),
..
datetime.date(2022,5,12))
date (2022,6,18))
datetime date(2022, 7,25))
(8,'Sophia','Jones',21,
'Female', 'Economics',
n (9, David', Decimal('3.55'), datetime.date (2022, 8,30))
is ,
'Martinee',24,'Male", " PoliticalScience',
z (10,'0livia','Taylor',20,'female",
D ecimal("3.92") datetime. date(20229,14))
Total psychology',Decimal('3.78' ), datetime
number of rowS retrieved= 10 .date(2022,
10,22)
)
160
oobJohnson
date time date C2022,3,
10))
,Male,Physs,
Deimal.
Alice'
datetimedate
willisms
(2022,
19,4emale
4,s)
, thurntsky'Duimals 31)
Data getaieved
wing fetchal
Ls, Chanlie'
Baaon23,Male'
datetimedate C222,,12)) t's.4c)
trginteing'ecimal
20,Eemale
dateine.date
BioloqyDecinalC3I6
C2022,G,18))
('Michael',Milen,
22Male',Bubiness,
Decimal 3.sc
datetime data (2022,,2s))
(s,Sophia,
Jones' 2,FemaleEconomick
',Decimal(3.sc)
datekime data C2022,&,go))
(9David' Mantinee ,24Male',
'olitical
Scence ,Decimal 3.92)
datetime date (2 022 9L, 1u))
'Olivia
13Lo, Taylus',
20,'Femal e',Pyckaloqy'DecimalC'st),
dattine.
date C2022, l0,
222>
4 Totol numbn of
DouMENTATLON
Subonited By
Bubmited on
Namei BAXia
ClasX
Signature
Teacher's ..
S
AlMi
to Caeate
KOnika progsam table in MysoL, nd add
display data aum itUsing python- Mysql inthae.
Lac
Stant
Vaiable
obile choice
data s input
andstoxe n arailable
C3eate insent quen
Enecute insot wsing
- I4 choice is 2:
-Execule select queI4 using
Cnsa
- Ifchaice is 3
- close connection.
chnie
-I4any othen display
Signature
Teacher's
as sqlTor
Amport mysql.connector
usera"root", passwordm "manager")
mycon sqlTor.connect(hostw"localhost",
cursor nycon. cursor()
("createtable ifnot
cursor.execute
mycon. commit ()
ifchoice ==
rn =
1:
int(input("Entex roll
nunber: "))
sn = input ("Enter yOur name: ")
mk = float(input("Enteryour marks: "))
query = "insertinto student values (I),,0) (rn,sn, mk)
".format
cursor.execute
(query )
mycon.commit ()
print
("## Record Saved #$")
e1if
choice = 2':
query = "select from student"
cursor.execute
(query)
result = cursOr.fetchall
()
£or i in result:
(i)
print
elifchoice ='3':
print("ByeBye..")
nycon.close()
break
else:
print
("*rong chote
entered")
ans = input
("Doouwant to
enterone more record?
(y/n): )
#
Display options even
if ans.lower() ifuser enters n'
n':
("1.
print Add record")
print ("2.
Display
print("3. Exit") records")
13.
ASK
0Ln to
Continue uddltr secursds..
CoDE
SooRCE
Conne chor
import myaql.
# Use
my school database
10
wso ereete C"Use my School"
mycon cemmjt ()
the databasc iS cgeated
indicating
paint
mesage
C"#*DatabasL e3eateo
tt ")
with to enter the Dop
20 ans = 4
ans
Initialize
2
Teacher's
Signature
S3
choiceinput
inpat (Enten
("Entenyeun choice i ")
)
29 i choice = '{':
30 In= int Cinput"Entengoll numben "))
Sn = input C"Entn 4Own name: ")
22 mk =
{loat input (" Enten your man K&i.
")>
32
quony insent intb Student values i3i3i3)
foxmat (an,Sn, mk)
Cwn soeecute
Lqurny
my con. Cormmi! ()
8 psnt ("#* Record Saved # ")
38
elif choìcc =='2'!
"Select * fsom student
quey
20
cwnsos eeiteLqueny)
Sesul! Cwnto fetchall
C)
paintCi)
Llt choice==3':
print('ByeBye.
Teacher's
Signature
DB.py
-RESTART: E:\sQL ##Python\create
## Databa se created
1.Add record
2. Displayrecords
3. Exit
Enteryour choice:1
Enterroll number: 12
Enteryour name: Akhila
Enteryour marks: 89
## Record Saved ##
Do you want to enter one more record? (y/n):
y
1. Add record
2. Displayrecords
3. Exit
Enteryour choice:1
Enterrollnumber: 19
Enteryourpáme: sagarika
Enteryour marks: 85
## RecordSaved ##
Do you want to enter
one more record?(y/n):
1.Add record y
2. Displayrecords
3.Exit
Enteryour ch0ice:1
Enterroll number:
14
Enteryour name:
Enteryour marks:harsha
92
.4.2
paint
"2.Display
paint ("3. Ex
choice:
Enten oll nAmben 12
want to enten
Display
3.. Exit.
Egtes Choice
youn.
Enten 19
gous oll numben
Enten name
Saganika
Enter
goun
#
Recosd SaNed # #
Teacher's
Signature
## Record Saved ## more record? (y/n):
y
Do you want toenter one
1.Add record
2. Display records
3. Exit
Enteryour choice:9
Wrong choice entered
Do you want to enter one more
record?(y/n):y
1.Add record
2. Display records
3.Exit
Enteryour choice:1
Enterroll number: 9
Enteryour name: siddhu
Enteryour marks: 88
## RecOrd Saved ##
Do you want to enter one more record? (y/n):
y
1. Add record
2. DisplayreGords
3. Exit
Enteryour choice:1
Enterzóll number: 7
Enteryour name: vaishnavi
Enter your marks: 85
## Record Saved ##
Do you want toenterone more record?(y/n):
n
Enteryour choice:2
(7, 'vaishnavi',
85.0)
(9, 'Siddhu',
88.0)
(12,'Akhila89.0) %
(14,'harsha',
92.0)
(19,'sagarika',
Do
85.0)
want to
you
1. Add record enterone more record?(y/n):
y
2.Displayrecords
3.Exit
Enteryour choice:3
Bye Bye..
12
4R
Enten you
cosd
manks :
aved
to entn
&s
One
Do you oant Teond ? (4In) n
DocOMENATLON
LoGilci
Statt
Date
Teacher'sSignature:
Expt.No. Page No. 2
SouRCE CoDE
my con=Sqlos.
Connetl Chosta localhost Usenot"pa ade"Avinash
2907,daabase ' myschoal)
myeon
1
t0,Studendupdate Fosm)
paint
to
# Eunttion to vie_all
data
12
def wieu_all data ():
13 CwNsos eNecute sELECT *FROM Student ")
all datei=
Hetcball
paint (n
t0., View AllData ")
paint (* 10)
20
21
99 Gew in alldata
Date Teacher'sSignature:
Amport mysql.connector as sqiTor
usere"ro0t";
passWorde"hvhnash 2907", databasemyschotwgm
mycon (hostw"]ocalhost",
sqltor.connect
Cursor mycon.cursOr(0
(****40)
print
print( 10, "studentUpda te Forn")
print(h* 40)
print("\n\n")
# Function to view alldata
def view alldata():
("SBLECT
cursot.execute FROM student")
all data fetchall
cursor. ()
("\n\n")
print
print("*n * 40)
print(" * 10, "View AllData")
print(han * 40)
print $ "rn",
("$l0s" "$20s"$ "Name", "$30s" "Marks")
forrow in all
data:
("t10s"row [0),"$20s"% row[1],"$30s" row[2])
print %
ifcursor.rowcount s0:
print("Sorryroll
number isnot found.
")
else:
prin10s""rn","$205" % % "Name", "$30s"% "Mar ks ")
for row in result:
print
("$10s"
% row [0],
"$20s"$ row[1),
"$30s"$ row [2])
choice = input("Are
you sure to update (y/n):
")
2f choice.lower()
== "y":
print
("Youcan updateonly name and marks.")
print("Eor updating roll nuer, contact
admin.")
Sn = input ("Enter
new name
mk = float(input("Entermarks
(leaveblank
to
ifyou don'twant to modify):)
update (0 to retainthe same): "))
sn = row[1]
if mk 0:
mk = row [2]
iflen(sn)> 0 and mk > 0:
update_queryUPDATE Student SET Snamem'()!,
cursor.exEcute marksmt) WHBRE rn={}".format
(sn, mk, rn)
(update query)
nyconComnit ()
24
26.
21
ans =
3S paint Sony, ll
numbn is not tound ")
else:
31 print ^108" . n" 20" ." Name, 30s"
Manks")
39
Date
Teacher's
Signature :
Expt.No.
So
Sn=
mk= ow C2]
33
i len tsn)>oand
opdate queny UPDATE Student SET Sname
63
# dose the Connecen
65 mycon. close C)
Date Toacher's Slgnature:
StudentUpdate Form
Enter roll
number to update: 12 Marks
Name
89.0
12 Akhila
Are you sure to update (y/n) :y
You can update onlname
and marks,
admin.
For updating roll number, contact :
Enter new name (leave blank you if
don'twant to modify) B Akhila
Entermarks to update to retainthe same): 0
o
View AllData
Name Marks
vaishnavi 85.0
9
siddhu 88.0
12 B Akhila 89.0
14 harsha
19 92.0
sagarika 85.0
Expt. No. 14 Page NoS
OutPUT
ARnila 29-0
Swre to
pdate
You can nOme and
opdateonly manks
View A Data
Name Manks
Vaish nai
Siddhu
12 BAhila
(4 hansha 42:0
19
Saqunikea
Date Teacher's
Slgnatura:
Student Update Form
rk******
Enter roll
number to update:12
Name
12 Marks
B Akhila 89.0
Are you sureto update (y/n):y
You can update oniy name and
marks.
For updating roll nber, contact
admin.
Enternew nane (leaveblank
Entermarks to update (0 to
if
you domt want to
:
modify)
Want tO update more
retain the sane): 91
(y/n) :
****k k*1
View AllData
k**************
k*** AN*** **
Nane
9 vaishnavi Marks
12 Siddhu 85.0
14 B Akhila 88.0
19 harsha 91.0
sagarika 92.0
85.0
Expt. No.
Page No.1
AIM
Wnite
coonech uith
pragam Ao.
My SoL datnbast.and
delete the
Sotenfote.
- Start
dlete queny
uing
cunsox ad displayappaopakale
- Lake ans a
con usn thy uoant to deleke maxe
as
import ysq.onnector sqlTor
mVCOnSRoE. connect (host="localhost",
user="yoot", database-"yschool")
password="nanager",
cursor)
cursoryoon.
print(40)
( *8,Student DeletionForm")
print
print(40)
while ans.lower ()
=='y':
rn=int ("Enterthe roli
(input number to delete")
)
query=selectirom Student where n=}".format (rn)
Cursor.execute
(query)
result=cursor.
fetchall
()
1f Cursor.roWCOunt==0;
print
("Roll " isnot
nyer ",rn, founa")
("Ais"$"Roll
print No","$20s"$"Name",
"$15s"$"Marks")
fow in result:
print [0),
("$10s"&row "$20s"row[1],
"&15st$row[2])
choice=input("Are you sure to delte the recoIdY/N:")
()=="y":
1fchoice.lower
query="delete from student where (rn)
n={}".format
Cursor,execute
(query)
mycon.COtunit)
print
("Record
deletedsuccessfully")
ans=input("Delete
more records y/n:")
Expt.No.
Page No 2
SoURCE CopE
paint "#"*
t
Student DaletionFoato"
7
6
pi t
yo)
while
Cunso
select
eyecute
4a0m Studem uahene n = "mat(n)
(2
Cqueny)
Cunsox tetchall
priot numbenTn,
Roll
elsei
2,"Manks)
E 4ox 0 in eMult :
Lpint "Zo
ongolaoilaiacPasbM
########################*########*##*####*
Student Deletion
Form
Enter
###################*################**####*
the roll number to
RollNo delete14
Name
14 Marks
Are yoisureto deltetheharsha 92.0
Recorddeleted recordY/N:y
successfully
Deletemore recordsy/n:n
Expt.No 5
Page No9
20
22
uey delete dsom student ohene an ={
22 CwIsos enecute
Caqueny)
24 mycon Commit C)
28 paind
ans = fnput (" Delete
("Recoxd deleted
kucusatully
QuTRT
DocumENTATION
Souxce code s Out put ne attached
Submitedon! Sutbnited
by
4olulas. Name AYaila
clasi) sno
Roll (2