0% found this document useful (0 votes)
8 views

PySql Connectivity

Uploaded by

bhabnish280707
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

PySql Connectivity

Uploaded by

bhabnish280707
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

..

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

Cwn so evecute celec cCommand.


Stoze data in vaniable
uaing fetchane C),fdh mexeC).
ond C). method&
etchall

SOWS ed
stox tn vaniables

Close cennechion to detabase

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.

6 data 1 = CwIsoT. etchone c)


data 2= Jeteh many )
data 3
jetchal o

10prairt

Lpatnt
Data 3eeeivec ing etochone C) corommand :n", data 1)
Data. xeclud uing fetch manyc) command: ")

pzint (i)

Spaint(Dota Jetived wting etch ai)conmarnd i")


paint (i

19Count =

t20 paint (Totatnumben c YOwS Cburt)

con

Dut Dut

Data celved USing fetchbne C) command


John', Doe, 20, Male', computen SceieneDecimal(a.7S)datehimedate
Del
3.
usin etchnoan ) commard

22,'
ceive d

42,Tarme',C
Data
Smith' Female Mathtmn ahci Decimal 3.90),

datetime dete Coe22, 9 2g))

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

Sownce Cade and Qut put ottached

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

Impost pythen MysqL comectiity module.


Initialize
cDnnechion to catabce host and Usen edentiale
qsing
nsing connettC) method andatoxe in Vaniable
mytan.
stose
Initialize object 4ox the Connectioncnd
nso

Vaiable

Caeake table equiy&d


tale does not
ot
is Ceated
database
Tsplay meage indicatingthe
Take choice xom uSen ocLwNence of uohile loop

obile choice

- Give choice to 8elect fox Addling ecod


to exit
2for display Yecoxds,3

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()

Createdatabase ifnot exists


("createdatabase ifnot exists
#
myschoo1")
cursor.execute

# Use myschool database


execute
cursor, ("use myschooI")

Createtable ifnot exists


existsstucdent(rnintprimary key, Snane varchar(30)nOt nsi1,
parks fioarsy
#

("createtable ifnot
cursor.execute

mycon. commit ()

# Displaymessage indicatingthe database iscreated


print("## Database Created #")

ans =y* # Initialize


ans with y' to enterthe loop

while ans.lower == ) 'y


print Add ("i. xord")
print("2.Dilay records")
print("3. Zxit")
choice = input("Enter
your choice:")

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.

mycon Esqllo Connecto(host localhost passd


managun
Cunso mycon Cun£0y )

6 * Cseate database i not exist


1 Cuns 03. eelte ca eate data bse i4 not existsmyseheal)

# Use
my school database
10
wso ereete C"Use my School"

# eatc table i not exlSts


12
cwt soT eXecute C"Caeate table not exiStS Student Cn int prima

key, Sname Voncha (30) hot


null,manks )
loat)"

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

while ans, lowen


paint 1 Add 3ecosd ")
aint C2.Displayseonds "
paint C.Eit

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

Data base Created #4


Add lcosd
2. Display gecoxd
8. Eouit

choice:
Enten oll nAmben 12

Entea mame Akhilo


Entes
goun manks
#Re cosd Sawed tt #

want to enten

Display
3.. Exit.
Egtes Choice
youn.
Enten 19
gous oll numben
Enten name
Saganika
Enter
goun
#
Recosd SaNed # #

Do y0u want to enten One moYe. Tecosd Cyln) y


Display secoNds

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

Enttn yoT chaice :


Enten oll numben: 1

Entn younmLmei Vaishnavi

4R
Enten you
cosd
manks :
aved

to entn
&s

One
Do you oant Teond ? (4In) n

DocOMENATLON

Sownce code and out put ane atached.


Expt. No. Page No ol
AIM
Wnile to view
praogsam. and updale ecosds ron a

Hable in My Sal uting pythb. My sal intažoce

LoGilci
Statt

Impoat aequixed MySGL conndox tibsauy


Estabish Connectio to te MsG1 databa with th

USer, pas wod and datab


Caeate a Cun so to eLeute SqL
quenics

Display a headen foy the Student updale tom.


Enten to
loap epeatecly update Itudent xUoxds kaaud on uu
ingut
Paoeapt the uwn to ente a oll humben to updat
Enecute. to etch te student detois
given goll numbon.

Ah aall numhen is not ound an


dsplay
ohuwoiše disflay the Student details
-Ask csiting
MOant to proceed with tae spdate
ahoose to
update
4 yes xecute a selt
queny to fetch and disgkuy
he updated gecoad.
want update mare xeCods.
Close th databse

Date
Teacher'sSignature:
Expt.No. Page No. 2

SouRCE CoDE

impoat mysql conntct as Sqttox

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 %

Nain update loop


ans =y
while ans == y Or ans =y':
("Enterroll
rn = int(input number to update:")
)

query = "SELECT *FROM StudentWHERE rn (".ormat


(rn)
cursor.execute
(query)
result= cursor.
fetchall ()

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 ()

ans = input("Want to update more (y/n):")


#View alldatà afterupdating
view alldata()
# Close the
connectíon
mycon.close()
Expt. No Page No 3
93

24

25 Main update loop

26.

21
ans =

ohile ans eY ox ant


2% on int Cinput("Enter
Koll mumben to update .
queny SELEcI EROM Sudent HERE gn2
CwnSo erealte
32 eult= eunsor.eteh
all )

3S paint Sony, ll
numbn is not tound ")
else:
31 print ^108" . n" 20" ." Name, 30s"
Manks")

39

choice a input CAge yo Sue to updaie (yln")


42

ipsint You can update anl name and maKs. ")

Date
Teacher's
Signature :
Expt.No.

pxin Cos updating callnumben Contauck


Page No 1
admin)

Sn input " Enten hew narne CleoNL olanK 4 pu don't


oant to rnsdify):

mk locLt Cinput ("Enten rnonks to supdate


do etain the Same)i )

So
Sn=

mk= ow C2]

33

i len tsn)>oand
opdate queny UPDATE Student SET Sname

maunks = {? HERE an3.


ox mat (sn,mk,n)
36
Cunsoeeute Cupdate quey
S1 ytoncomnit )

ans fnput "IAlant to apdale more

# iew all data cuyten


updating
62 view alL data C

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

Want to update more (y/n) : n

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

Student Update Foxm

Enten rol numben to update i2


N ame MOnks

ARnila 29-0
Swre to
pdate
You can nOme and
opdateonly manks

Fox Boll numben contoct admin


updating
Enten Cleaue
blank you don' ant to
modity)B
AKhila
Enttn manks to update o to getaio the same) o

want to update moe

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

Inpent3quixedpytnen MysqL connectiuity module


2aitializeconnection to hast
dat abask ay cing uen and
Caedertials and Stage Yaniable
InitializeCunsoX above Connection aod store in a vaniable
ns y', thant a ohile
Initializlg
while Ouns ==)o
- Take ollno a input
-Erecute select CAnsor
queny ng
eunsox and displa to usen
no gesulte match
duplay
-gesultound
-hiplayStudent detuil.
- Tale input fsom USen
cong'xming oleletion.
- Usen contisme thun delete gecoxd buy execette

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

impont mysal. Connectex

mycon Sql:Tm cOnned Chost


localhoswoot"
pas otord
mancgen "databas myschool")

paint "#"*
t

Student DaletionFoato"

7
6
pi t
yo)

while

Sh= nt input("Entethe soll umbn to delete )

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

Choice = inpt Ant you lwne to delete the geLond

Date Teachar's Signature:


bseoipartut

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

Student Dde tion

Enten the nuum ben to delete14.


RollNo
Name anks
hasha q2.0
Aze youSane to delete

Rend deleted suceeštully


Delete more Tccosds y/n n

DocumENTATION
Souxce code s Out put ne attached
Submitedon! Sutbnited
by
4olulas. Name AYaila
clasi) sno
Roll (2

Date C13 lal3s Teachar's Slgnature :

You might also like