You are on page 1of 14
INTERFACE PYTHON WITH SQL While developing real life applications, we need to connect it with database in. CHAPTER CHECKLIST rks os Sane enki atest wks the tats ced dates sed ns hc rmanipulatedichanged. Python allows us ro connect our application to the Connecting to dics Hic ive raving ‘SQlite and many lea ‘MySQL from Python In this chapter, we will discuss Python - MySQL connectivity and learn to Creating Table perform different database operation in python. +» Insert Operation © Update Operation CONNECTING TO MYSQL Delete Operation FROM PYTHON Read Operation User can write Python seripe using mysql. connector library after installing Python MySQL connector. [tan connect to MySQL databases from Python, Install mysql connector "To cece the Pye application wiki MySQL dae we ai Tp ie jap ec eee ns pg “The nape eoencci ta bib a 92 ll at (Ring crusade coll ing py Sal, >python -m pip tnstall nysql-comector Ifyou are using Anaconda Jupyter then type flowing command on terminal onda tnstaMl -¢ anaconda aysql-connector-python Steps for Creating Database — Connectivity ve ee There a vats ep fr eating debe connec a fee follows Step 3. Creating the conor object Step 1 Import nyeq.connecroe module Tiare feet tliat 1 api pe i cat ach sheacron that specified in Python DBLAPE itonbycoesed papers ereraiay tore msl -comector oe sake pene ole gh = Se Soe ‘import mysql .connectar as mat can be create using cusor () method of Cconnesvon obec Itisanimporsntterm othe ‘Here, mya ian identifier which canbe choose Praesent eet by wer Syntax ‘Step 2 Create the connection object furser_shjct = eamectionebsect ‘Te creme « comecsion bermeen the NASOL cearsor() daabae and Python aplicion, we connect) en ‘method mysql. connector module is wed. Pass 2 Backs the databace dele ike HostNeme, Usewamee cont me and daake Prato, Tes method scruc the connection joc, Syne Gaenection abject ‘ys -comector.comect| print (com furser = con cursor¢) 7 ae eg put ‘heart aysql connector nso. connector connection MySQL can = mysql. curmecter-cemact( ‘connection objecrat O x 7b 14204¢780> host = "Tecalhest™ MySQUCuzaoe: (Noshing excited ye) Step 4 Execute the Query ‘Ae: creating the cusce, SQL query can be excusing cee) Funcvon. peice) = Syma o— sason Cursor. cbect. este (ery) Step 5 Clean up the environment lf you waneto connect specie dba, you Tis ie the ial ep for crating desoee have specify the database came in connec) scomcciiy. There is acesury to close the oT ‘conneston which you crested 2 Sym cornectiononjeet.close\) ‘pace ays -comector us oma comic ce ng Wetoeind de crested localhest” tlecnncion ue lowing cman To Show the List of Existing Database {if you wan display the name ofall existing dstbase, use folloning query Dhow éatatases Import mse corrector on = mys). comnector.comectt est = “Teetbost”, passed = “arthart") curser = cence) @ ~ curser execute(“how dtabases") except i, rollback) torn cursor: pews) coatelese() Ourpue (information schems) Cay) Compe) Ces) Creating the New Database To create the new database, we fllowing command Syntax erste database (taba ate) 2 port mse corrector 5 eomneetor. comet Cursor = cxn.cursort) te cursor cxeutet‘ereate database Python (2) = curser.exeaste("snow datatases") cet. in roVbaeke) tort in eveeor pee) con-cleset) Ourpue (Python 8") (information schema’) Creating Table ‘Weecan create a table wing CREATE TABLE statement. Stas CREATE TARLE Tobe Rane q columt datatspe constrait lum? datatypo constraint Column datatype > Hire, we wil crete cable Student in database PythoaD with five columns as Name, Clas, RollNo, Address and Boreatage, 2: Import mysileanrector on = ny) connecter cornet (ost = “ecatnost user = “ret”, pasead = “arthant™ Guatase = “Pthente") cursor = con.cursor() ter ~ cucsor.exosute (orate table Stuer (ane Varhir CONOT WALL, Pato Ine(10} Primary bay Class varcheis. adress varchar 80) Percentage Float (1601) cot an-rotback¢) con.closet) In Fyshon stell, o> ase Fynonte Database chaned so dese Stent 5 rons 19 48t 06 200 Alter Table LF user wants to alter existing table, ALTER TABLE statement ised Syntax ALTER TABLE Table Rano AED Celuneano Catatyps 4g: We wil dd new column Agein table Snadent. Inport mysql conector con = ayia’ corncctor cxmact (host = “lecsThos ser = “roat’, passa = “acthant™ fSarabase ~ “Fythet) curser = can.cursor() ty cursor extutet‘atter tabla Stant add ge tats) wot rll”) except con. back) con-cleset) In Python shel Doodese Student Check Point 01 1 re commando itl comet for MSL we Hp 2 Which command i edt cleanup the emronmeni? 5 Wrtethe satement excite the query 4 How tdsply the name of pre-ccrtagdtabase? 5 Whats these af cusorO meshed? Insert Operation Inset opention i squred when you wane tm cre yout ‘eros Ice a dabuss ble INSERT INTO aatemeni is ted madd a record 1. Add Single Record into a Table In Python, coadd single record ins ale we canmmesion the fomnat specifier (ts) m pce oF value Example withou format specifier ‘mort ysl cenrector en = nysql-cornectorcomect (host = “TocaTnst” asin! = “artart”, Gatabase = “Pyttorte") curser = con curcar() sal = “nate toto Stuart (ane, alive, Class, mares. Percentage, gp) vile Ua" 23.12. Deh 715" ty carsac.cite (se) fonesaet exept oa. colbie censzTsa(), Example with formatspecfer ‘nport mys. cooacter an = ayql-comctor.comect (oort = “ovat” pasted = arta dauaase = “Pytbett”) cusae = eam cursor) fal = “naert Into Stuert aa, fel Wo, Cass, aebess, Feccotae gp Jutlas (Ry 26,26, He, B,D” volues = CRIgt", 7.32, “bln 72,18) "cursor execute(sql. values) ton coeett() cep on. aback east) In Fyshon skell Sooselece "ron student: 2. Insert Multiple Rows or Records You can also insert multiple records at atime. To insert rmulkiple records, uee format specifier (So) maker i ey Foc Us GaniemitgO) ete! briaine H cans meee than one satemente together. os re esq) canrecter con = wy) connsctorcomect (past = “Tecainst” passed = “acthant Satabace = “Python™) cursse = con eursor() ‘sal = “tasert into Stucert (nae, pollo, Class, Ares Percentage, gp) values CR. 45, 15, 15, 15) values = Cans", 33, 11, “pelht", 97, 14), Cniean?. 23. 1 Pune", Bt, 1, cmsnas, 28, 12, “Weerat” 98, 163] ty cursor. encutenary (sel values) comme) excest conc baek() con.ceset) In Pychon Stell, enselectoteen Student: eae aaa eee Update Operation Update operation means to update one or more records on ny databur, which are alent exo in thet databee. For ths, UPDATE surement is wed. Syntax WEORTE Table Name SET column Name = value WERE fenartioe cog In Student sable, we will update che clase of chose seudent whore Rell No is 22. ‘import ays cenvactor on = mysql -cornectorcamect Inast = “lecaltast, user = “rot, passed = “aethant™ facabase = “Pytnete) curser = cxn.cursort) cursor.exeute *ipcate Student set (late = 12 shore BollNa = 227) xn cont) excest cont back) on.ceset) In Fython Shell Delete Operation “This operation is required when you want to dete some recor Fim the datase Fer sh, DELETE. FROM pacierre Syntae SELETE FROH Tale Rane WERE cotton ce In Sede table, we will eee the record ofthat student whose Rall No 3. Wper mst. camerter on» yl comectorcomeet (rose = “heanest”, ter = "ent pated = “rian” fetoase = “yenote") cxrete = eam.ctet) wy cxreae crite (let them Sur were thie =) cen comttt) excep: en rotoaskcd ceo.closet) tn Python Shel, SSLICT On stent; Read Operation This operation & used co fetch some wif information from the databese By fllowing methods, you can fech the daca fom database 1. fetchone() Teceruns the nex row fom the result eas tuple. IF there ae no mote rown t rezieve, None is returned, eg: To fetch only one record tngort. myst) comector on = mys. comnectar.comest tnast = “ecatost”, wer = “ret pated = “eran” curser = cen.cursort) cursr.enecute "Select Nae, AoTNo. Aedress. Fercentage fram aisply = cursor fetcrene() rintidisela) ecert can otibac) e.lese() Ourput (Ria, 27, Deb’ 73) 2.fetchmany ({size}) Ie returns she number of tows spaced by the size argument. When called repeatedly this method feches the nexese of rows ofa query resul and nuns als of tuples. Tepe more roe are avalible rene am empty le eg To fetch many records from database PychonDB Inport mse conector on = mya. comnetar comest inast = “ecahost”, ser = “oot passid = "ethan" database curser ~ cencurzort) tw 2120 = Intiput(“Eter tha value of runers of r¥s.")) Cursor exettetSelect*from Staten") Aisply = cersorfotermany si) fort tn rapa: eine it) cco can. otibeck) con. eset) Onur Student") Python") ‘Enter the value of 20. oF rows : 2 (Riga, 27, 12, ‘Dell, 73,15) (Kiran, 22, 12, ‘Dela, 88, 15) 3. fetchall() Te etches all the rows of query result. It reurns all he rows a a isc of rules. An empy ists rerarned if there is no record to fetch 2g. To fetch all cords fiom database PythonDB mort mysql careccter con = mysql comector.comect (host = “locates paced = “acthant antanase = “Pythonoe™) cursoe = 600 cursor() wy cursor_owcute ("select tran Student") arsplay ~ cursor. tetchatlo) ‘rt 19 diplay peveect) cert cnn-roTibact (9 con.cTosat) Cupar (Riya, 27, 12, ‘Delt, 73, 15) (Kiran, 22, 12, ‘Delt, 88, 15) (Nhs, 28,12, "Meerut, 95, 16) Y reweount isi rae ny atte ad returns the rember cos that wer aed by an exe meted Check Point 02 1 Which format specif isused te adda recond ints we? 2 When isexecuienany statement ased? 2. During the fchone) math, thre arene mare rove o ‘emer, then wr valaewil bereumed? 4 How istchll) fer from ftckmary0? EXAM PATTERN EXERCISE OBJECTIVE Type Questions Directions (Q. Nos. 1-8) There are multiple choice type (uettions. Select the correct option. 4. User can wnite Python script using (2) MySOLconnector ibrary (@) SQLconnect library (6) MySOLcomnectlibrery (@) any one ofthe sbove Ans. (3) MySQL comectr library 2. Which ofthe following method is used to create «connection between the MySQL database and Python? (o)eommecien (ent) Ane. (beannact() (@) connest() (@cont() 3, Whatie default value ofhost? (a) Host (@)locamost (6) globe host (None ofthese Ans. (b)lceaost, 4, Which command is used to dsplay the name of ‘existing databases? (c) display databases (e oupatastabases; Ans. (o)stow dasa 5. ___ operation is required when you want to ‘create your recerds into a database table. (a) Update (Delete (e) Bead (test Ans. (@) insert 6. Whieh method returns the next row from the resultset astuple? (4) fetctove () (e)fetchall() Ans. (a)fecione() (@) Fetchmany () (@rowzount Directions (Q. Nos. 7-11) Fil m the blanks. 7, tan connect to MySQL databates from Python, Ans MysoLcomect 8. Themysqlconnector is built in module. Ans. net 9, __ method returns the connection abject. Ans. connect () 10, __canbe create using cursor () method of ‘connection object Ans. Cursor abject, 1, ___ statement is used to adda record, Ans BSERT INTO Directions (0. Nos. 12-19) Answer the fllowing questions 12. Whatis database connection? Ania A dasbaen conantion ina fcey i compton thar alowe cient sofware to tle to datbare srver Sefiware, whether onthe sane machine o not (3, Whatis database connectivity? Ans. Databsce i an oppbestion programming interface (APD whch ows the programaner fo connect ad inerat with cabs, |, Which command sused to import siyegl.connecter pechage with an identifier? ‘epert ysl comector as identi Tier mane “6 ans ‘ayortaysql.comector sya 15, How tocreste a connection object? Ans, conwoetson eject = mysql connector comect ( (nest = Hoste, see = User pated = password) 16. Define the fetchmany (sie). Ans fatchnany(ie) noturnethe stnber of rove paciad od faces hens ot fro geyser and eturs ist of tuples io more row re Seaiabl, t returns an empty lat 17. How fetztone () method safer from feteha) method? ‘Ans. (exctove() method returas the nex sow fom there Sets pte whe fachal () father athe vow of 8 gue reslt 18. What concitons or terms areinclude by DB-API? Ane. + Importing tho AP male ‘Argun seonnecion with dbase Sore procedures nd esingSOL statements + Cong the conection 19. Write the command to add s column salary in table Employee ‘Ans. ALTER THLE ployee AD salary IntQ0): SHORT ANSWER Type Questions |. Which data will get addedin table Company by following code? ‘mort myselccnrector on = nysa!.cornector.comect ( host = Toeainest™ sor = “aysten", passed = “het ‘acabase = “coeneet™) cur = coe. cursor (°) fal = "eseet nto Company (ana, Dept Salary) values (18.35, 85)" val = (A807, “Oea", 35000) tur execute (sel, vat) neon) ‘Ans "C7, “DBK", 36000 2. Thetable Company of database connect ‘contains te following records ‘Sab ‘What will be the autput af fallawing code? Inport mysql conector on = nysqi-cornector.coment (ost = “lecalnest™ pasied = ‘hello’, ‘atabase = ‘coméct") cur = con.cesoe() cur execute ("select Rane, Salary fron Company") ‘teplay ~ eur fetctora() petnecatsplay) Ans. (ABC, 35000) 3. Wilte the code tocreate the connection in which databatet name ix Python, name af host, liter and paseword can taken by user Also, print that connection. ‘epert nysql.comactor syean ~ ays. comectorcomect( rest = calnest Ans titer = “test” pasoed = “eesinata fetebese = Python) prteeycan) 4. Wile the code to create atable Product in database Inventory with following fields Fists Datatype Po veoh) Piers hart a Ans. eport mysqh-comectar sycan = myScomector connect, (host = “locales. ser = "syste" passed = "hello", (atanase — Toventory”) cur = meen cursor () ur enceute (GREATE TABLE Producten (@1D varchar (6) Pemaey bey, Pranechar (30). price oat Fane varener(2))9" sycan.close( ) 5. Givenbelow i table iter in database Inventory. eniD HenName Queniy Uritrce mA a a Riya created this table but forget to add column ManufacturingD ate. Can she add ths coluren after creation of table? i yes, write the code where user's name and password are system aanditeat respectively. Ans. Ans Ans. Yes she can add new columa ser creation of te. ‘woot ays. comector sycon ~ nyqlsonnectorcomeet( host = “localhost” user = “Sst passed = “est fstanase — “Inventory”? cursor = yea. cursor cursor execute ALTER TALE Ito 600 NanatacturgDate tate oT MUL") syem.cose ¢) Consider the following table structure “Table: Faculty with felas as Frame fire ate salary ‘Write the Python code to ereate the above table. ‘eport aye]. comoctor sycan = mysql. carmectorconect ( nest = "localnest” see = “root” pasoed — “rystan’, Satssase = “Soci? cursor = aycan cursor ) dh = curso. axzeute ("CREATE TABLE Frealty ( F.1D varchar (3) Primary hey, Fame varcnar (30) NOT NLL, Lame varcnar (88) tee dota Date, sale'y Foa0)) smem.close () Consider the table Persons whoveflelds are LID, LastName, FirstName, Addrese, Cy ‘Wilte a Python code to add a new row but add date enly in the P 1d, LastName anc columans as 5, Peterson, Kari respectively ‘eport nysl.conmectar ct = aysqlommector-comect (host = “localhost” pass = “aimnn23" eatibace ~ "yster") cursor = can cursor ( fsal> “INERT INTO fersons (P10, Lactan, Firstaae) 1Aiues (8. Petersin", “ar ty cursor eeuute (291) Ans Ans concent () except ten.relToack (> xn close () (Consider the table Student whoveflslde are ‘SCODE Noms Age simde Poins Gre 2 Aun 13. Nu Tioga ss Witte the Python cede to update grade to'A' for all hese students who are geting morethan § as points. ‘epert mysql. comestor a5 ayo con = mpd comect (host = “lcaThest™ cursor = cor-cursor () St] = “WPOME Stutert SET rade = WERE Points > wy cursor. extte (340) cxn-comit (> except fen. relTback (> xn choca () ‘Arexultet ie extracted from the database using, the cursor object (that has been already created) by giving the following statement ICESE SOP Term rgatercurserfetcnonet) (i) How many zecarde willbe returned by fetchone() method? (Gi) Wrat valle the datatype of Mydata abject after the given command is executed? (@ fetchone() method retrieves the next row ofa query feail et and otras a dagle sequence, or aonelf it ‘hore rovs ate avaiable So one record wil Be ‘retuned ty fetchorel) method (i tuplethe dnsatype of pda object er the piven Command is executed. Tuples ae ed store eterogeneoas elements, Which are elements Belonging to different dita types. Write the code to create the following table Student with the following fields RollNo FirstName LastName Ans. 4 oi Ans. Address Contacto Marks Course Rank Inthe table, Rank should be Good Fest, Bad Worst, Average. ‘ep0"t ays. comoctor syeon = ay connector connect ( hast = “Toeatbost", ash = “systen" fatabace = “Seroi") cursor ~-meon-cursot ( ) ab = cursor sccate (CREATE TABLE Student rate Ire) Primiy bay Festione sarchar(30) NOT WL, Lasuiase varerar(3), fairess varenar(50) Contacto varenae(20), ets Float, Course chart), Rank ena) ohael (Rank IN Ee "tad “worst”, Average") 9) syem close ( } Consider the table Faculty whose columns! 10 Fre. Lane He dt, Sarg Write the code to insert the following record Intethe above table et’ Fie | Shama [202008 | s6t00 | Jee Advance Rogan mien | s122010 | 2000 | aa Smucue ‘eoort mysql. conmectar sycon ~ nyqlsoanector connect (ast = “locales. User = "root", passid = “gysten", databace = Test”) cursor = conearsor ( Sal = “INSERT INTO Fecuty (FID, Fone, Late, Hire dite. Seaty (Course tana) ALES is, 15, 43, 15, 15.3577 eq. aya’, “snarea”, “i2-i0-20n8". 2600. “dave ‘avance’), (102, Keys wishra’, “3-12-20 ‘ata Structure’) “coo, tr cursor. exceutenaey (5. val) Ans B. Ans acon conatt () except rmyeonrolback 9 syean clase () (Consider the table MobileStock with following ‘elds td, Mane, HLcty, Suoplter Write the Python cede to fetch all records with fields M_Id, M_Name and M Supplier from database Mobile ‘epert ysl comector aye sycan = mydb_comect (tost = “localhest” lor — Troe”, pated cursor = sycon.curso® ( ) fee “SET Ht. fo, Sup cr fron noitescc™ w eercimmens fell ateply = srsor. ‘etal ( fer tn dieslay sem 1) enceot treo roti spain coe ¢ Consider the folowing able Traders with following elas cade Tae omy Te sim Stee Cop tabi — Tia Din iuee be Grr Write Python code to display the names of those traders who are either fram Dela or from Mambal ‘epert aysql. connector sycan = mysql.comector comet thest = “Tecalost™. user = “oct” passed — “systen" atatase = "Attn" st yeon. cursor () SELECT FROM Trators MERE City ~ Mamet” OF Efty = Boths"* ty cursor. cxecutet sat) is = cursor. fetsnall ( ) for 1 in dso: pemnt (1) except fear rolIbak year clase () LONG ANSWER Type Questions 1. Create totiowin table using Pytnon cade where Databuse Tet Teble Watches Username - Root Paseword — System Walenid WatctName — Pace soe High Tne 10000 109 “Listens 8000 150 High Fecsen 7000 Unese 260, (Gider ma 25000 Gans 100, Ans. ‘eport ays] -conector sy = aye. canmoetar consct (host = “TocaThest™ User = Root”, passed databace = Test”) cursor = my cursor) fy = cursor_exzcate ("CREATE THBLE Matches (watch Id varenar(8) Primary Hey. syster, xemns ctar(Z0) MOT MILL, Petes Maat, Type vernar (2), Oty store tetis) MOT MLL))® eat = “DISET 170 watenee acctd, watcha Free, Type, ky store) TALES (is. 18, 35. 3.10)" val = {(7900", “high Thee 20000, "unisex", 100), cy002","“Lite Tine", 16000, “adios”, 160, va0s", wave", 2000, “Sents", 200) ra04", “Hiohrashin’, 7000, “untsex., 250), 1005", “Gatden Tne", 26000, “aents", 1007) ty cursor. excutemany (Sql, 21) sy conte) excent vy roibaet ) sy-close () 2. Here stable club Menbedd Menbename Address Age Fee 3 Nain New Di 21 2100 ‘Write the Python code forthe following (i) Update the Address of member whose Mombertd i M002 wth News (a) Detete te record of those member whese ames Sachin. Ane (9 seport mysql sonoetor turser scouts (“UPDATE Club SET acres ~ Netde” WERE Wanborlé = aay) yon comntt excopt ryconraTback ( 9 sycon-clese () (9 sport sysat. comectar sycon = nysq comectorcomect (fost = “acsthest user = "Aan, pasted = "Aden@123" Grtabase = “ysten") curser = aycon. cursor (-) try: curser scouts (“DELETE FRO Club eke remernare = Sace" curser.comtt) except: rycon-roTback ( ) sycon-clese () 3. Consider the table MobileMaster so1ecaia 201-120 power ‘Wilt the Python code forthe following To display details of those mobiles whose priceis greater then 2000. (i) To mereate the price of mobile Samsung by 2000. Ans. (0 teport mysql -comector 26 yd syean = nya.comect (host = “TaevThost™ pasoxd = “systen’, datatate ~ “Adee") cursor = aycon-cursor () sq] = “SELET * FROH Mbt Tetaster WERE M Price > ator” uy: eursor_aweuts (s81) Atsplay = cursor. fetenall ( for 1 19 display pevetct) except: syeon-roliback syeon.clate ©) (ay tmpre aysal-comector as myc sycon = aydbcomect (host past database cursor = year cursor () Sg] = “UPDATE Mabrletester SET H Price merice + 2000 WERE Conany = vy: cursorexecute (341) ryenn.conatt owcopt jean caTback ( ) syomn-close 4. Write the Python code for (I) and il} on the basis of table College Sansuna’* Ane No Name Age Oeparinont Outotlon Gan Sor Tien SI Natersies 201 es 2 fees 27 Chematy —16f2e4 e000 F 2 Wren 42 Nahenates 02/100 coco 4 Poach 2 Fyses 170202 e000 5 Staaz 45 Boog 15/2Rs 10500 © Uneth 29 Boingy Aa sO (i) To insert snev rowinthe table College with thefellawing data 15, atin". 77 Physics’, "15/05/02", 8500."M (G) Te delete a row from table which name is (6 sayoreaysal.comactor 15 aya con = mye senmoet fost = "leatnest”, ser = “raat” ated ~ "aie", fatatase = “ranagenen") cursor = con cursor () fq) = “TNSERT INTD Collage iM, Nae ‘ge, Departnene, DatestDon, asic, Sex) WALES (05, “#tin', 27, "Pystes', ‘Sies/0' 808, “8 ) curse axoesta (<1) eoncclese () (sport mysal-conactor as myth con = nyc somoct (ost = “Toes Taest™, ser = "rot", passa = ‘adnn@i2e" atabece ~ “wanagonont") curser = con cursor () try: curser acest (OELETE FROM CeTTeg8 CRE None = "Viren" "> corcommit | except eae roTbace con-elese () | CHAPTER TEST | OBJECTIVE Type Questions Directions (Q. Nos.1-5) There are muhiple choice type (questions. Select the corect option. | Whats an identiner in following commana? “gore ayeal.comctor 35 cb (a)amport @ymysqh : (6) connector On si 2. Toadd anew column into.atable, wath ‘commandis used? (Q)4LTERTABLE ——_(@) UPDATE FROM (6) INSERTINTO (@)allof hese ‘To {insert multiple records into table, which method is uted to execute statement? (a) execute () ()executemany () (c)executenl () (None ofthese 4. Which of the following statement is correct? (Q)DELETE INTO (b) DELETE TABLE. (o DELETE ALL (@) DELETE FROM, 5 iefetches al therows of aquery result. (e)fetchall() () fotehenany () (6) fetcnmnote() (@ afer () Directions (Q. Nos. 6-10) Flin the blanks. 6 Cursor objest canbe create using — method of ‘connection object 7 After creating the cursor, SQL query ean be ‘execute using function. & Toads recordintotable, we can mention — inpiaceof value ‘9 We can create atable using statement. 10 _can connect tomysa} database from Python. Directions (Q. Nos. 11-15) Answer thefallowing questions. {1 Write the command te import the connection ‘of Pytnon with MySQL. 12. Define the fetehone() method. 13. How fetchmany () method e difer rom fetchall)) method? 14, Wieke the command to update the table Exmployee with Salary column, change the salary of those ‘employee who have computer skills with 25000. 15 Whatdo you mean by read operation? HORT ANSWER Type Questions 16 Create the connection of Python with MySQL, inwhieh ‘statace name ~ Syste User = Adan Pasgeerd = AeP123 17 Wrte the code to create atabie stationery in database School with fellowing fields Fes Deyo Code Vachon) Name cago ‘by ist 18, Which data will get added in the table Mobile by following cc ‘port. sql connector syeon = magi -carnecter connect Tocainest™, see = “Aan” pasta’ ~ "Aden@23" atabese = “cowee:") yeu. cursor ( ) NSERT INTO Mabe Mano, He ries, Oty) WAU Cs, 35, 25, 15)" Sansung™. “Gila Fé, 23000, 3) cursor-ereute’(a].¥a1) sycon commit ( 19 Consider the table Inventory with following fields ID, Name, Qty, Amount, Manufecturing Date. Witte the Python code to fetch ellrecords with flelds ID, Name, Qty, Amount from databace, (Consider the table Employee whose eolurana! £10, eplane, Jotntnbate, Salary. bopartmort ‘Wilt the code to insert the following record 5 Uvesi 7 Siooyy 1ouues asco F Intothe above table “6 Towra 35 Vatharaton Cond 0500 e101 | im | 210-2008 ant DBA 22 Consiter the table FLI oe |Sandesn| 70100 | oeo| Bese ait eek menses: __, No Swing Endng ha Fgh ho Spe LONG ANSWER Type Questions 01 Mims OR D 21 ceeteflloing table using Python code Crs0_engley obi 2 Sabie college NCKGt nive Morb 8 7MEI2 Kanpur Benours 3 Write the Python code forthe following (i) To display cetats of thoze fights whose rnumber of fights greater than. 2 Patch 24 Chemisty s10uD2_7500_ (Gi) To increase the numberof fights of Sight Indove vo Mumbai by 8

You might also like