You are on page 1of 22

VIJAYALAKSHMIiDINESH

2214101657

MASTERiOFiCOMPUTERiAPPLICATIONi(MCA)

THIRDiSEMESTER

DCA8142

OPEN-SOURCE DB SYSTEM
SETi1i&iSETi2

Q1.iWhatidoiyouimeanibyiConcurrencyiControl?iExplainidifferenticoncurrencyicontrol
iproblems.
Answer
ConcurrentlyicontroliisiaiveryiimportanticonceptiofiDBMSiwhichiensuresitheisimultaneousie
xecutioniorimanipulationiofidataibyiseveraliprocessesioriuseriwithoutiresultingiinidataiincons
istency.iConcurrencyiControlidealsiwithiinterleavediexecutioniofimoreithanioneitransaction.
Iniaidatabaseimanagementisystemi(DBMS),iconcurrencyicontrolimanagesisimultaneousiacces
sitoiaidatabase.iItipreventsitwoiusersi from editing the same record at the same time and also
serializes transactions for backup and recovery.
Theicoordinationiofitheisimultaneousiexecutioniofitransactionsiiniaimultiuseridatabaseisyste
miisiknowniasiconcurrencyicontrol.iTheiobjectiveioficoncurrencyicontroliisitoiensureitheiseri
alizabilityiofitransactionsiiniaimultiuseridatabaseienvironment.iConcurrencyicontroliisiimport
antibecauseitheisimultaneousiexecutioniofitransactionsioveriaisharedidatabaseicanicreateiseve
ralidataiintegrityiandiconsistencyiproblems.iTheithreeimainiproblemsiareilostiupdates,iuncom
mittedidata,iandiinconsistentiretrievals.

1.iLostiUpdates:
Theilostiupdateiproblemioccursiwhenitwoiconcurrentitransactions,iT1iandiT2,iareiupdatingith
eisameidataielementiandioneiofitheiupdatesiisilosti(overwrittenibyitheiotheritransaction).iCon
sideritheifollowingiPRODUCTitableiexample.
OneiofitheiPRODUCTitable’siattributesiisiaiproduct’siquantityionihandi(PROD_QOH).
Assume that you have a product whose current PROD_QOH value is 35. Also assume that two
concurrent transactions, T1 and T2, occur that update the PROD_QOH value for some item in
the PRODUCT table.Theitransactionsiareiasifollows.
iTwoiconcurrentitransactionsiupdateiPROD_QOH:
iiiiiTransactioniiiiiiiiiiiiiiiiiiiiiiiiOperation
T1:iPurchasei100iunitsiiiiiiiiiPROD_QOHi=iPROD_QOHi+i100
T2:iSelli30iunitsiiiiiiiiiiiiiiiiiPROD_QOHi=iPROD_QOHi–i30
i
TheiFollowingitableishowsitheiserialiexecutioniofithoseitransactionsiunderinormalicircum
stances,iyieldingitheicorrectiansweriPROD_QOHi=i105.

Butisupposeithatiaitransactioniisiableitoireadiaiproduct’siPROD_QOHivalueifromitheitableib
eforeiaipreviousitransactioni(usingitheisameiproduct)ihasibeenicommitted.

TheisequenceidepictediinitheifollowingiTableishowsihowitheilostiupdateiproblemicaniarise.
Noteithatitheifirstitransactioni(T1)ihasinotiyetibeenicommittediwhenitheiseconditransactioni(
T2)iisiexecuted.iTherefore,iT2istillioperatesionitheivaluei35,iandiitsisubtractioniyieldsi5iinim
emory.iInitheimeantime,iT1iwritesitheivaluei135itoidisk,iwhichiisipromptlyioverwrittenibyiT
2.iInishort,itheiadditioniofi100iunitsiisi“lost”iduringitheiprocess.

2.iUncommittediData:

iTheiphenomenoniofiuncommittedidataioccursiwhenitwoitransactions,iT1iandiT2,iareiexecute
diconcurrentlyianditheifirstitransactioni(T1)iisirolledibackiafteritheiseconditransactioni(T2)ih
asialreadyiaccesseditheiuncommittedidata—
thusiviolatingitheiisolationipropertyiofitransactions.

Toiillustrateithatipossibility,ilet’siuseitheisameitransactionsidescribediduringitheilostiupdatesi
discussion.iT1ihasitwoiatomicipartsitoiit,ioneiofiwhichiisitheiupdateiofitheiinventory,itheioth
eripossiblyibeingitheiupdateiofitheiinvoiceitotali(notishown).iT1iisiforceditoirollibackidueitoi
anierroriduringitheiupdatingiofitheiinvoice’sitotal;ihence,iitirollsibackiallitheiway,iundoingith
eiinventoryiupdateiasiwell.iThisitime,itheiT1itransactioniisirolledibackitoieliminateitheiadditi
oniofithei100iunits.iBecauseiT2isubtractsi30ifromitheioriginali35iunits,itheicorrectianswerish
ouldibei5.
TransactioniiiiiiiiiiiiiiiiOperation
T1:iPurchasei100iunitsiiiiiPROD_QOHi=iPROD_QOHi+i100i(Rollediback)
T2:iSelli30iunitsiiiiiiiiiiiiiiiiiPROD_QOHi=iPROD_QOHi–i30

TheifollowingiTableishowsihow,iunderinormalicircumstances,itheiserialiexecutioniofithoseitr
ansactionsiyieldsitheicorrectianswer.

TheifollowingiTableishowsihowitheiuncommittedidataiproblemicaniariseiwhenitheiROLLBA
CKiisicompletediafteriT2ihasibeguniitsiexecution.

3.iInconsistentiRetrievals:
Inconsistentiretrievalsioccuriwheniaitransactioniaccessesidataibeforeiandiafterianotheritransac
tion(s)ifinishiworkingiwithisuchidata.iForiexample,ianiinconsistentiretrievaliwouldioccuriifitr
ansactioniT1icalculatedisomeisummaryi(aggregate)ifunctionioveriaisetiofidataiwhileianotherit
ransactioni(T2)iwasiupdatingitheisameidata.iTheiproblemiisithatitheitransactionimightireadiso
meidataibeforeitheyiareichangediandiotheridataiafteritheyiareichanged,itherebyiyieldingiincon
sistentiresults.
i
Toiillustrateithatiproblem,iassumeitheifollowingiconditions:
i1.iT1icalculatesitheitotaliquantityionihandiofitheiproductsistorediinitheiPRODUCTitable.
2.iAtitheisameitime,iT2iupdatesitheiquantityionihandi(PROD_QOH)iforitwoiofitheiPRODUC
Titable’siproducts.
TheitwoitransactionsiareishowniinitheifollowingiTable

WhileiT1icalculatesitheitotaliquantityionihandi(PROD_QOH)iforialliitems,iT2irepresentsithei
correctioniofiaitypingierror:itheiuseriaddedi10iunitsitoiproducti1558-
QW1’siPROD_QOHibutimeantitoiaddithei10iunitsitoiproducti1546-
QQ2’siPROD_QOH.iToicorrectitheiproblem,itheiuseriaddsi10itoiproducti1546-
QQ2’siPROD_QOHiandisubtractsi10ifromiproducti1558-
QW1’siPROD_QOH.iTheiinitialiandifinaliPROD_QOHivaluesiareireflectediinitheifollowingi
Table

Theifollowingitableidemonstratesithatiinconsistentiretrievalsiareipossibleiduringitheitransacti

oniexecution,imakingitheiresultiofiT1’siexecutioniincorrect.iThei“After”isummationishownii

niTablei10.9ireflectsitheifactithatitheivalueiofi25iforiproducti1546-

QQ2iwasireadiafteritheiWRITEistatementiwasicompleted. Therefore, the “After” total is 40 +

25 = 65. The “Before” total reflects the fact that the value of 23 for product 1558-QW1 was

read before the next WRITE statement was completed to reflect the corrected update of

13.iTherefore,ithei“Before”itotaliisi65i+i23i=i88.
Theicomputediansweriofi102iisiobviouslyiwrongibecauseiyouiknowifromitheipreviousiTablei
thatitheicorrectiansweriisi92.iUnlessitheiDBMSiexercisesiconcurrencyicontrol,iaimultiuserida
tabaseienvironmenticanicreateihavociwithinitheiinformationisystem
2.ia)iWhatiareitheidifferentistrategiesiofiOSSilicensing?
Answer
TheiOptimizationiStrategy
"TheioptimizationistrategyiisianiopenisourceimanifestationiofiClaytoniChristensen'si"lawiofic
onservationiofimodularity."iInitheiOSSiapplicationiofiChristensen'silaw,ioneilayeriofiaisoftw
areistackiisi"modulariandiconformable,"iallowingiadjacentisoftwareilayersitoibei"optimized."i
Theimodulariandiconformableilayersiareicommodities,iandiareiunprofitableiorionlyimarginall
yiprofitableisoftwareibusinesses. The Linux operating system is an example. The disruption
caused by a modular and conformable operating system such as Linux serves to erode margins
for other operating system vendors like Sun, Wind River, and Microsoft. Winners under
Christensen's law are the adjacent, interdependent layers of the software stack, the layers where
applications are optimized to achieve greater
value,iandiwhere,icorrespondingly,ibetteripricingipoweriexists.iOracleiprovidesianiexampleio
fianioptimizediadjacentilayer,iasianiROIiassessmentibyiMainstayiPartnersiillustrates.
TheiDualiLicenseiStrategy
Underitheidualilicenseistrategy,iaisoftwareicompanyioffersifreeiuseiofiitsisoftwareiwithisome
ilimitations,iorialternativelyioffersiforiaifeeicommercialidistributionirightsiandiailargerisetiofi
features.iInitheidualilicenseiapproach,ifreeiuseicarriesicertainiconditions;itypically,ianyimodif
icationsithatiareidistributedimustialsoibeimadeipubliciinisourceicodeiform,iandicompaniesica
nnotiuseitheifreeiversioniasiaicomponentiofianyiproductiorisolutionitheyicommercialize.iThis
ipreventsithirdipartiesifromidevelopingiimprovementsithatiwouldirivalitheioriginaliopenisour
ceisoftware.
Thisistrategyiisiofteniassociatediwithithei"FreeiCore,iAdded-ValueioniTop"ibusinessimodel.
"RoaringiPenguiniSoftwareiInc.istartediasiaione-
personiconsultingicompanyiini1999.iAiyearilater,iDavidiF.iSkoll,itheicompany'siPresidentian
diCTO,iwasiaskeditoidevelopianie-mailifilteringitool.iDavididevelopediMIMEDefang,ianie-
mailifilterithatiusediSendmail'siMilterifacilities.iDavididonateditheicodeitoitheiopenisourceic
ommunity,iandikeptidevelopingiMIMEDefangiasiaifreeitooliforisystemiadministrators.iToday
,itheiMIMEDefangicodeiisiavailableiatiatitheiwebsite.
Byi2002,iitiwasiobviousithatithereiwasiaineediforiaipackagedimail-
filteringisolutionisuitableiforiend-
users.iDavididecideditoigoiaheadiandiwriteiwhatibecameiCanIt-
PRO.iWhereasiMIMEDefangiisisuiteditoisystemiadministratorsiwhoiareifamiliariwithiPerlian
dicomfortableiwithiwritingitheirifilteringipoliciesiiniPerl,itheiCanItiproductilineiallowsiend-
usersitoicontrolitheirifilteringithroughiaisimpleiweb-basediinterface.
Theicompanyitransformediitselfifromiaiconsultingicompanyitoiaiproductidevelopmenticompa
ny.iThisitransformationirequiredisignificantichanges.
Thereiareiainumberiofiopenisourceibusinessimodelsitoutedibyiopenisourceisupporters.iRoarin
giPenguinichoseithei"freeicore,ivalue-
addionitop"imodel.iTheicoreiscanningisoftware,iMIMEDefang,iisifreeiandireleasediunderithei
termsiofitheiGNUiGeneraliPubliciLicense.
AllitheiMIMEDefangicodeiisicontributedibyiRoaringiPenguin,iwhichihasimadeiminoripatche
siandiregularireleasesibasedionicommunityifeedback;iMIMEDefangiisiestimateditoihaveibet
weeni6,500iandi10,000iusers.
TheicommercialiproductsiareibuiltionitopiofiMIMEDefangiandihaveiaimoreitraditionalipropri
etaryisoftwareilicense.iHowever,ievenitheicommercialiproductsishipiwithisourceicodeiandipe
rmissioniforiend-usersitoimodifyiit.iTheyijustican'tiredistributeitheicommercialiproducts.
TheicommercialisoftwareiextendsiMIMEDefangibyihookingiintoistrategicipointsiiniitsifilterif
ile.iMIMEDefangiwasidesigneditoibeiextendediinithisiwayibyisystemiadministratorsiandiitipr
ovediainaturaliwayitoidevelopiCanIt.
Althoughisomeibusinessesiofferionlyifreeisoftwareiandigenerateirevenueistrictlyifromisupport
ioricontracticustomizations,iweididinotifeelithisiwouldigenerateisufficientirevenueitoimakeith
eicompanyiviable.iWeibasedithisifeelingioniainumberiofiobservations:
TheiConsultingiStrategy
Accordingitoiai2000iU.S.iDepartmentiofiCommerceireport,inotisincei1962ihasipackagediso
ftwareiinvestmentireachedi30%iofitotalisoftwareiinvestment.iSoiLinuxiorinot,isoftwareilice
nsesiareiearningiaismalleriportioniofiinformationitechnologyi(IT)iinvestment,iwhileiconsulti
ngiandiservicesicontinueitoirise.

AccordingitoiRediHat,itheioperatingisystemicomprisesionlyi4%iofitheioverallirevenueiofiai
Linux-basedisolution.

TheiSubscriptioniStrategy
AccordingitoiCulpepper,i"revenuesifromiservicesi--ibothimaintenanceiandiconsultingi--
iincreaseiiniproportionirelativeitoirevenuesifromilicenses.iMoveioutitoithei20-
yearimark,ianditheitypicalisoftwareicompanyiwillihavei$2iofiservicesiforieveryi$1iofilicens
es."
TheiPatronageiStrategy
WhyiwouldiaicompanyilikeiIBM,iorianyicompanyiforithatimatter,icontributeitime,ienergy,i
developers,iandicodeitoianiopenisourceiorganization?iThereiareiainumberiofistrategicireaso
ns.iIBMidoesiititoidriveistandardsiadoptioniandicrackientrenchedimarkets.iWheniaicompan
yicontributesiopenisourceisoftwareitoianiindependentiorganization,iitianticipatesithatiaide-
factoistandardiandisupportingicommunityiwilliconvergeiaroundithaticontribution.iAicompan
yimayialsoiuseitheipatronageistrategyitoicommoditizeiaiparticularilayeriofitheisoftwareistac
k,ieliminateicompetitorsithatiareiextractingirevenueifromithatilayer.iForiexample,iIBM,iasia
imajoricorporateipatroniofiLinux,iseeksitoicommoditizeitheix86ioperatingisystem,ieliminati
ngiserverifeesiforiMicrosoftiWindowsiandiSuniSolaris.iThisicreatesianiopportunityiforiIBM
itoi

offerivalueihigheriupitheistackithroughiclustering,iavailability,iprovisioning,isecurity,iandim
anagementisoftware.

Toisucceediwithiaipatronageistrategy,itheipatronimustideliverimoreithanijustisourceicode.iT
hereimustialsoibeileadershipiandiconsistency.

IBMihasibeeniveryifocusedioniwhereiitiappliesiitsiopenisourceienergies.iTheicompanyihasi
aniOpeniSourceiSteeringiCommitteeithatihasiapprovedimanyiOSSiinitiatives.iIBM'siOSSiin
itiativesiareiclearlyivestediiniserveristrategiesiasiopposeditoitheidesktop.iAsiairesultiofisuch
ifocus,iIBMihasisucceedediinicommoditizingitheiSuniSolarisioperatingisystemiandiinislowi
ngidowniMicrosoftiserveriadoptioniinitheidatacenter.iItihasimadeinoiheadwayiyet,ihowever,
iinibreakingiupitheiMicrosoftiOfficeidesktopimonopoly.
TheiHostediStrategy
CompaniesilikeiSalesforce.com,ieBay,iandiGoogle,iareiinitheisoftwareibusiness,ibutitheyido
n'tisellitheirisoftware,itheyiletiyouiuseiitiorirentiit.
TheiEmbeddediStrategy
Linuxiisitheioperatingisystemiusediinimoreithanihalfiofitheiembeddedisystemsimarket.iItiha
sibeeniusediiniconsumeriproductsisuchiasiTIVOiandiinidevicesilargeiandismall,ifromiserver
sitoicelliphones.iThroughoutitheiworldiitiisirapidlyibecomingitheioperatingisystemiofichoic
eiforimanyilow-costicommunicationsiproducts.
2.b)iBrieflyiexplainitheiissuesirelatediwithicopyrightiandipatents.
Answer
Issuesirelateditoicopyright
Theiissueioficopyrightihasigotteniincreasinglyicomplexiandidifficultiinitheidigitaliage.iGive
nitheibroadiavailabilityiofidigitalitechnologies,icopying,idistributing,iandimanipulatingidigit
alicontentiisinowieasierithaniever.iThisihasiresultediiniseveralicopyrightidifficulties,isuchias
ipiracy,iinfringement,ianditheiunlawfuliuseiofiprotectedimaterials.
Followingiareisomeiofitheimostiimportanticopyrightiissuesiinitheidigitaliagei−
Piracyiisioneiofitheimostiimportantiproblemsiinitheidigitaliage.iItiinvolvesitheiillicitiduplica
tioniandidistributionioficopy-
protectediworks,isuchiasimusic,ifilms,isoftware,iandibooks.iInimanyipartsiofitheiworld,ipart
icularlyiinidevelopinginationsiwhereicopyrightirulesiareinotieffectivelyienforced,ipiracyiisi
widespread.
Infringementioccursiwhenisomeoneiutilisesicopyrightedicontentiwithoutiauthorizationioricre
dit.iThisiincludesitheiuseioficopyrightediphotosiorivideosioniaiwebsite,itheiuseioficopyright
edimusiciiniaivideoioripodcast,ianditheisaleiofiproductsiwithicopyrightediimagesiorilogos.
airiUseiisiailegalidoctrineithatipermitsitheiuseioficopyrightedimaterialsiforispecificipurposes
,iincludingicommentary,icriticism,inewsireporting,iteaching,ischolarship,iandiresearch.iYet,i
theinotioniofifairiuseiisifrequentlyiopenitoiinterpretation,iandiiticanibeichallengingitoievalu
ateiwhetheriaispecificiuseioficopyrightedimaterialiqualifiesiasifairiuse.
DigitaliRightsiManagementi(DRM)iisiaisetiofitechnologiesiuseditoipreventiunauthorisedidu
plicationiandidistributionioficopy-
protectedicontent.iNonetheless,iDRMihasibeenicriticisediforirestrictingiusers'ilegaliandifairi
useioficopy-protectedicontent,isuchiasigeneratingibackupicopiesiofidigitalicontent.
Copyrightirulesivaryigreatlyifromicountryitoicountry,imakingiitidifficultitoienforceicopyrig
htilawsiinitheidigitaliage.iThisihasiresultediiniseveraliworldwideicopyrightiinfringementila
wsuits,iespeciallyiinitheimusiciandifilmiindustries.
Theiissueioficopyrightiinitheidigitaliageiisidifficultiandimultidimensional,ibutithereiareiainu
mberiofipotentialisolutionsithaticouldihelpicontenticreators,iconsumers,iandiregulatorsiover
comeitheirichallenges.iHereiareisomeipossibleisolutionsi−
Improvingitheiimplementationioficopyrightirulesiisioneiofitheimostieffectiveistrategiesitoic
ombaticopyrightiviolationsiinitheidigitaliage.iThisimayiinvolveiincreasingifinesiforicopyrig
htiviolations,iwideningitheiextentioficopyrightiprotection,ieasyianditimelyilegaliprocedureit
oihearitheicases,iandienhancingiinternationalicooperationionicopyrightienforcement.
Educationiandiawareness:iAnotherisolutioniisitoiraiseiconsumer,icontentiprovider,iandipolic
ymakerieducationiandiunderstandingioficopyrighticoncerns.iTheseimayiinvolveipubliciawar
enessicampaigns,iinstructionaliresourcesiforicontenticreators,iandipolicymakeritrainingionic
opyrightilawiandiitsiinfluenceionitheidigitalieconomy.
Q3.iExplainitheifeaturesiandidataitypesiofiPostgreiSQL.
Answer
A data type specifies what kind of data you want to store in the table field. While creating a
table, for each column, you have to use a datatype. It identifies a particular type of data, like
integer, Boolean, floating points, and so on.
Inithisisection,iweiareigoingitoidiscussitheivariousidataitypesiusediiniPostgreSQL.
IniPostgreSQL,ieachidatabaseitableihasimanyicolumnsiandihasipreciseidataitypesiforieachic
olumn.iItisupportsianiextensiveirangeiofidataitypes.
Also,iusersicanicreateitheiricustomidataitypeiusingitheiCREATEiTYPEiSQLicommand.iAn
ditheseidataitypesihaveitheifollowingiadvantages:
Performance:Itienhancesiouriperformanceiifiweiareiusingitheseidataitypesicorrectlyiandieffi
cientlyitoistoreitheidataivalues.
Validation:iTheicorrectiuseiofidataitypesiinvolvesitheivalidationiofidataiandidismissaliofidat
aioutsideitheiscopeiofitheidataitype.
Compactness:Itistoresiefficiently,iasiaicolumnicanistoreiaisingleitypeiofivalue.
Consistency:iTheiactivitiesiinicontradictionioficolumnsiofitheisameidataitypeiprovideireliab
leiresultsiandiareiusuallyitheifastest.

IniPostgreSQL,iweihaveimanyisetsiofidataitypes;iletiusiunderstandithemioneibyione:

Numericidatatype
Characteridatatype
Date/timeidatatype
Monetaryidataitype
Binaryidataitype
Booleanidataitype
Enumeratedidataitype
Geometricidataitype
Textisearchidataitype
UUIDidataitype
Networkiaddressitype
JSONidataitype
Bitistringitype
XMLidataitype
Rangeidataitype
Arrays
Compositeidataitype
Objectiidentifiersitype
Pseudoidataitype
pg-Isnidataitype
NumericiDataiType
Numericidatatypeiisiuseditoispecifyitheinumericidataiintoitheitable.iItcontainsitheifollowing
four-iandieight-byteifloating-pointinumbers
two-,ifour-,iandieight-byteiintegers
Selectable-precisionidecimals.
TheibelowitableicontainsiallinumericidataitypesithatisupportiiniPostgreSQL:
Name description storage range
isize
smallint storesiwholeinumbers,ismallirange. 2ibytes -32768itoi+32767
integer storesiwholeinumbers.useithisiwhe 4ibytes -2147483648itoi+2147483647
niyouiwantitoistoreitypicaliintegers.
bigint storesiwholeinumbers,ilargeirange. 8ibytes -
9223372036854775808itoi9223372036
854775807
decimal user-specifiediprecision,iexact variable upitoi131072idigitsibeforeitheidecimal
ipoint;iupitoi16383idigitsiafteritheideci
malipoint.
numeric user-specifiediprecision,iexact variable upitoi131072idigitsibeforeitheidecimal
ipoint;iupitoi16383idigitsiafteritheideci
malipoint.
real variable-precision,iinexact 4ibytes 6idecimalidigitsiprecision.
doubleipr variable-precision,iinexact 8ibytes 15idecimalidigitsiprecision
ecision
serial autoiincrementingiinteger 4ibytes 1itoi2147483647
bigserial largeiautoiincrementingiinteger 8ibytes 1itoi9223

CharacteriDataiType
IniPostgreSQL,iweihaveivariousigeneralipurposeicharacteridataitypes,ianditheseidataitypesi
areiuseditoirepresentitheicharacteritypeivalues.
TheibelowitableicontainsialliCharacteridataitypesithatiareisupportediiniPostgreSQL:
Datatype Explanation
char(size) Hereisizeiisitheinumberioficharactersitoistore.iFixed-
lengthistrings.iSpaceipaddedionirightitoiequalisizeicharacters.
character(size) Hereisizeiisitheinumberioficharactersitoistore.iFixed-
lengthistrings.iSpaceipaddedionirightitoiequalisizeicharacters.
varchar(size) Hereisizeiisitheinumberioficharactersitoistore.iVariable-lengthistring.
characterivarying(size) Hereisizeiisitheinumberioficharactersitoistore.iVariable-lengthistring.
text Variable-lengthistring.

Q4.iExplainitheiPHPicontrolistructures.
Answer
Control Structures are at the core of programming logic. They allow a script to react
differently depending on what has already occurred, or based on user input, and allow the
graceful handling of repetitive
tasks.iIniPHP,ithereiareitwoiprimaryitypesiofiControliStructures:iConditionaliStatementsiand
iControliLoops
ConditionaliStatementsi:
ConditionaliStatementsiperformsidifferenticomputationsioriactionsidependingioniconditions
.iIniPHP,itheifollowingiareiconditionalistatements
ifistatement
ifi-ielseistatement
ifi-ielseifi-ielseistatement
switchistatement
☞iifistatement
Theiifistatementiisiuseditoitestiaispecificicondition.iIfitheiconditioniisitrue,iaiblockioficodei
(if-block)iwillibeiexecuted.
Syntaxi:
ifi(condtion)
{
statements
}
ifi-ielseistatement
Theiif-
elseistatementiprovidesianielseiblockicombinediwithitheiifistatementiwhichiisiexecutediinit
heifalseicaseiofitheicondition.
Syntaxi:
ifi(condtion)
{
statements
}
else
{
statements
}
ifi-ielseifi-ielseistatement
Theielseifistatementienablesiusitoicheckimultipleiconditionsiandiexecuteitheispecificiblocki
ofistatementsidependingiuponitheitrueiconditioniamongithem.
Syntaxi:
ifi(condtion1)
{
statements
}
elseiifi(condtion2)
{
statements
}
elseiifi(condtion3)
{
statements
}
else
{
statements
}

switchistatement
Theiswitchistatementienablesiusitoiexecuteiaiblockioficodeifromimultipleiconditionsidepen
dingiuponitheiexpression.

Syntaxi:
switchi(expression)
{
casei1:istatements
break;
casei2:istatements
break;
casei3:istatements
break;
.
.
default:istatements
}
LoopiStatementsi:
Sometimesiweimayineeditoialteritheiflowiofitheiprogram.iIfitheiexecutioniofiaispecificicod
eimayineeditoibeirepeatediseveralinumbersiofitimesitheniweicanigoiforiloopistatements.

IniPHP,itheifollowingiareiloopistatements

whileiloop
doi-iwhileiloop
foriloop
☞iwhileiloopistatement
Withitheiwhileiloopiweicaniexecuteiaisetiofistatementsiasilongiasiaiconditioniisitrue.iTheiw
hileiloopiisimostlyiusediinitheicaseiwhereitheinumberiofiiterationsiisinotiknowniiniadvance.
Syntaxi:
whilei(condition)
{
statements
}
doi-iwhileiloopistatement
Theido-
whileiloopiwillialwaysiexecuteiaisetiofistatementsiatleastionceianditheniexecuteiaisetiofistat
ementsiasilongiasiaiconditioniisitrue.

Syntaxi:
do
{
iistatements
}iwhilei(condition);

Example
html>
<head>
<title>Do-WhileiDemo</title>
</head>
<body>
<h1>Do-WhileiDemo</h1>
<?php
$n=1;
do
{
iiiiechoi"$ni<br/>";
iiii$n++;
}iwhile($n<=5);
?>
</body>
</html>

JumpiStatementsi:
JumpistatementsiiniPHPiareiuseditoialteritheiflowiofiailoopilikeiyouiwantitoiskipiaipartiofia
iloopioriterminateiailoop.
IniPHP,itheifollowingiareijumpistatements
breakistatement
continueistatement
☞ibreakistatement
Theibreakiisiaikeywordiiniphpiwhichiisiuseditoibringitheiprogramicontrolioutiofitheiloop.ii.
e.iwheniaibreakistatementiisiencounterediinsideiailoop,itheiloopiisiterminatediandiprogrami
controliresumesiatitheinextistatementifollowingitheiloop.
Theibreakistatementibreaksitheiloopsioneibyione,ii.e.,iinitheicaseiofinestediloops,iitibreaksit
heiinneriloopifirstianditheniproceedsitoiouteriloops.iTheibreakiisicommonlyiusediinitheicas
esiwhereiweineeditoibreakitheiloopiforiaigivenicondition.
Syntaxi:
break;
continueistatement
Theicontinueistatementiiniphpiisiuseditoibringitheiprogramicontrolitoitheibeginningiofitheil
oop.ii.e.iwheniaicontinueistatementiisiencounterediinsideitheiloop,iremainingistatementsiare
iskippediandiloopiproceedsiwithitheinextiiteration.
Theicontinueistatementiskipsitheiremainingilinesioficodeiinsideitheiloopiandistartiwithithein
extiiteration.iItiisimainlyiusediforiaiparticulariconditioniinsideitheiloopisoithatiweicaniskipi
someispecificicodeiforiaiparticularicondition.
Syntaxi:
continue;

Q.5iWriteiainoteionitransactionsiandicursors.
Answer

Cursor
CursoriisiaiTemporaryiMemoryioriTemporaryiWorkiStation.iItiisiAllocatedibyiDatabaseiSe
rveriatitheiTimeiofiPerformingiDML(DataiManipulationiLanguage)ioperationsionitheiTable
ibyitheiUser.iCursorsiareiuseditoistoreiDatabaseiTables.i
Thereiarei2itypesiofiCursors:iImplicitiCursors,iandiExplicitiCursors.iTheseiareiexplainedias
ifollowingibelow.
ImplicitiCursors:iImplicitiCursorsiareialsoiknowniasiDefaultiCursorsiofiSQLiSERVER.iTh
eseiCursorsiareiallocatedibyiSQLiSERVERiwhenitheiuseriperformsiDMLioperations.
ExplicitiCursors:iExplicitiCursorsiareiCreatedibyiUsersiwheneveritheiuserirequiresithem.iE
xplicitiCursorsiareiusediforiFetchingidataifromiTableiiniRow-By-RowiManner.
HowiToiCreateiExplicitiCursor?
DeclareiCursoriObject
Syntax:
DECLAREicursor_nameiCURSORiFORiSELECTi*iFROMitable_name
Query:

DECLAREis1iCURSORiFORiSELECTi*iFROMistudDetails

iii
i2.iOpeniCursoriConnection
iSyntax:
OPENicursor_connection
Query:
OPENis1
FetchiDataifromitheiCursoriThereiisiaitotaliofi6imethodsitoiaccessidataifromitheicursor.iThey
iareiasifollows:i
FIRSTiisiuseditoifetchionlyitheifirstirowifromitheicursoritable.i
LASTiisiuseditoifetchionlyitheilastirowifromitheicursoritable.i
NEXTiisiuseditoifetchidataiiniaiforwardidirectionifromitheicursoritable.i
PRIORiisiuseditoifetchidataiiniaibackwardidirectionifromitheicursoritable.i
ABSOLUTEiniisiuseditoifetchitheiexactinthirowifromitheicursoritable.i
RELATIVEiniisiuseditoifetchitheidataiinianiincrementaliwayiasiwelliasiaidecrementaliway.
i
Syntax:
iFETCHiNEXT/FIRST/LAST/PRIOR/ABSOLUTEin/RELATIVEiniFROMicursor_name
FETCHiFIRSTiFROMis1
FETCHiLASTiFROMis1
FETCHiNEXTiFROMis1
FETCHiPRIORiFROMis1
FETCHiABSOLUTEi7iFROMis1
FETCHiRELATIVEi-2iFROMis1
Closeicursoriconnection
Syntax:
iCLOSEicursor_name

Query:
CLOSEis1
Deallocateicursorimemory
iSyntax:

DEALLOCATEicursor_name
Query:
DEALLOCATEis1
HowiToiCreateianiImplicitiCursor?
AniimpliciticursoriisiaicursorithatiisiautomaticallyicreatedibyiPL/SQLiwheniyouiexecuteiai
SQListatement.iYouidon’tineeditoideclareioriopenianiimpliciticursoriexplicitly.iInstead,iPL/
SQLimanagesitheicursoriforiyouibehinditheiscenes.

ToicreateianiimpliciticursoriiniPL/SQL,iyouisimplyineeditoiexecuteiaiSQListatement.iForie
xample,itoiretrieveiallirowsifromitheiEMPitable,iyouicaniuseitheifollowingicode:
Query:

BEGIN
iiFORiemp_reciINiSELECTi*iFROMiempiLOOP
iiiiDBMS_OUTPUT.PUT_LINE('Employeeiname:i'i||iemp_rec.ename);
iiENDiLOOP;
END;
In PL/SQL, when we perform INSERT, UPDATE or DELETE operations, an implicit cursor
is automatically created. This cursor holds the data to be inserted or identifies the rows to be
updated or deleted. You can refer to this cursor as the SQL cursor in your code. Thi SQL
cursor has several useful attributes.

%FOUNDiisitrueiifitheimostirecentiSQLioperationiaffectediatileastioneirow.
%NOTFOUNDiisitrueiifiitididn’tiaffectianyirows.
%ROWCOUNTiisireturnsitheinumberiofirowsiaffected.
%ISOPENichecksiifitheicursoriisiopen.
Iniadditionitoitheseiattributes,i%BULK_ROWCOUNTiandi%BULK_EXCEPTIONSiareisp
ecificitoitheiFORALListatement,iwhichiisiuseditoiperformimultipleiDMLioperationsiationc
e.i%BULK_ROWCOUNTireturnsitheinumberiofirowsiaffectedibyieachiDMLioperation,iwh
ilei%BULK_EXCEPTIONireturnsianyiexceptionithatioccurrediduringitheioperations.
Query:

CREATEiTABLEiEmp(
iiiiEmpIDiINTiPRIMARYiKEY,
iiiiNameiVARCHAR(50),
iiiiCountryiVARCHAR(50),
iiiiAgeiint(2),
iiSalaryiint(10)
);
--iInsertisomeisampleidataiintoitheiCustomersitable
INSERTiINTOiEmpi(EmpID,iName,Country,iAge,iSalary)
VALUESi(1,i'Shubham',ii'India','23','30000'),
iiiiiii(2,i'Amani',ii'Australia','21','45000'),
iiiiiii(3,i'Naveen',i'Sriilanka','24','40000'),
iiiiiii(4,i'Aditya',ii'Austria','21','35000'),
iiiiiii(5,i'Nishant',i'Spain','22','25000');
iiiiiiiSelecti*ifromiEmp;

NeediofiCursoriinianiSQLiserver
Cursorsiallowiusitoiprocessidatairow-by-
row,iwhichicanibeiusefuliwheniweineeditoiperformicomplexicalculationsioritransformation
sionitheidata.
Cursorsiallowiusitoiiterateioveriairesultisetimultipleitimes,iwhichicanibeiusefuliwheniweine
editoiperformimultipleioperationsionitheisameidata.
Cursorsicanibeiusefuliwheniweineeditoijoinimultipleitablesiwithicomplexirelationships,isuc
hiasiwheniprocessingihierarchicalidataistructuresioriwheniperformingirecursiveiqueries.
Cursorsiallowiusitoiperformioperationsisuchiasiupdating,ideleting,ioriinsertingirecordsibas
edionisomeiconditionioricriteria.
Cursorsiareiespeciallyiusefuliwheniprocessingidataifromimultipleitablesiwhereitheirelation
shipsiareinotistraightforward.
SQLi–iTransactions
Aitransactioniisiaiunitiofiworkithatiisiperformediagainstiaidatabase.iTransactionsiareiunitsior
isequencesiofiworkiaccomplishediiniailogicaliorder,iwhetheriiniaimanualifashionibyiaiuserior
iautomaticallyibyisomeisortiofiaidatabaseiprogram.

Aitransactioniisitheipropagationiofioneiorimoreichangesitoitheidatabase.iForiexample,iifiyou
iareicreatingiairecordioriupdatingiairecordiorideletingiairecordifromitheitable,itheniyouiarei
performingiaitransactionionithatitable.iItiisiimportantitoicontrolitheseitransactionsitoiensure
itheidataiintegrityianditoihandleidatabaseierrors.

Practically,iyouiwilliclubimanyiSQLiqueriesiintoiaigroupiandiyouiwilliexecuteialliofithemitoge
theriasiaipartiofiaitransaction.
PropertiesiofiTransactions
Transactionsihaveitheifollowingifouristandardiproperties,iusuallyireferreditoibyitheiacronym
iACID.
Atomicityi−iensuresithatiallioperationsiwithinitheiworkiunitiareicompletedisuccessfully.iOthe
rwise,itheitransactioniisiabortediatitheipointiofifailureiandiallitheipreviousioperationsiareirol
ledibackitoitheiriformeristate.
Consistencyi−iensuresithatitheidatabaseiproperlyichangesistatesiuponiaisuccessfullyicommit
teditransaction.
Isolationi−ienablesitransactionsitoioperateiindependentlyiofianditransparentitoieachiother.
Durabilityi−iensuresithatitheiresultiorieffectiofiaicommitteditransactionipersistsiinicaseiofiais
ystemifailure.
TransactioniControl
Theifollowingicommandsiareiuseditoicontrolitransactions.
COMMITi−itoisaveitheichanges.
ROLLBACKi−itoirollibackitheichanges.
SAVEPOINTi−icreatesipointsiwithinitheigroupsiofitransactionsiiniwhichitoiROLLBACK.
SETiTRANSACTIONi−iPlacesiainameioniaitransaction.
TransactionaliControliCommands

TransactionalicontrolicommandsiareionlyiusediwithitheiDMLiCommandsisuchiasi-
iINSERT,iUPDATEiandiDELETEionly.iTheyicannotibeiusediwhileicreatingitablesioridroppingith
emibecauseitheseioperationsiareiautomaticallyicommittediinitheidatabase
TheiCOMMITiCommand
TheiCOMMITicommandiisitheitransactionalicommandiuseditoisaveichangesiinvokedibyiaitra
nsactionitoitheidatabase.
TheiCOMMITicommandiisitheitransactionalicommandiuseditoisaveichangesiinvokedibyiaitra
nsactionitoitheidatabase.iTheiCOMMITicommandisavesiallitheitransactionsitoitheidatabaseis
inceitheilastiCOMMITioriROLLBACKicommand.
TheisyntaxiforitheiCOMMITicommandiisiasifollows.
COMMIT;
Example
ConsideritheiCUSTOMERSitableihavingitheifollowingirecordsi−

+----+----------+-----+-----------+----------+
|iIDi|iNAMEiiiii|iAGEi|iADDRESSiii|iSALARYiii|
+----+----------+-----+-----------+----------+
|ii1i|iRameshiii|ii32i|iAhmedabadi|ii2000.00i|
|ii2i|iKhilaniii|ii25i|iDelhiiiiii|ii1500.00i|
|ii3i|ikaushikii|ii23i|iKotaiiiiii|ii2000.00i|
|ii4i|iChaitalii|ii25i|iMumbaiiiii|ii6500.00i|
|ii5i|iHardikiii|ii27i|iBhopaliiii|ii8500.00i|
|ii6i|iKomaliiii|ii22i|iMPiiiiiiii|ii4500.00i|
|ii7i|iMuffyiiii|ii24i|iIndoreiiii|i10000.00i|
+----+----------+-----+-----------+----------+
Followingiisianiexampleiwhichiwouldideleteithoseirecordsifromitheitableiwhichihaveiagei=i2
5ianditheniCOMMITitheichangesiinitheidatabase.
SQL>iDELETEiFROMiCUSTOMERS
iiiWHEREiAGEi=i25;
SQL>iCOMMIT;
Output
Thus,itwoirowsifromitheitableiwouldibeideletedianditheiSELECTistatementiwouldiproduceit
heifollowingiresult.
+----+----------+-----+-----------+----------+
|iIDi|iNAMEiiiii|iAGEi|iADDRESSiii|iSALARYiii|
+----+----------+-----+-----------+----------+
|ii1i|iRameshiii|ii32i|iAhmedabadi|ii2000.00i|
|ii3i|ikaushikii|ii23i|iKotaiiiiii|ii2000.00i|
|ii5i|iHardikiii|ii27i|iBhopaliiii|ii8500.00i|
|ii6i|iKomaliiii|ii22i|iMPiiiiiiii|ii4500.00i|
|ii7i|iMuffyiiii|ii24i|iIndoreiiii|i10000.00i|
+----+----------+-----+-----------+----------+
Q6.iExplainiaboutiDataimanagementiiniInnoDB.
Answer
InnoDBiisiaigeneral-
purposeistorageiengineithatibalancesihighireliabilityiandihighiperformance.iIniMySQLi8.0,i
InnoDBiisitheidefaultiMySQListorageiengine.iUnlessiyouihaveiconfigurediaidifferentidefau
ltistorageiengine,iissuingiaiCREATEiTABLEistatementiwithoutianiENGINEiclauseicreatesi
aniInnoDBitable.
ItsiDMLioperationsifollowitheiACIDimodel,iwithitransactionsifeaturingicommit,irollback,I
andicrash-
recoveryicapabilitiesitoiprotectiuseridata.iSeeiSectioni15.2,i“InnoDBianditheiACIDiModel”

Row-level locking and Oracle-style consistent reads increase multi-user concurrency and
performance. See Section 15.7, “InnoDB Locking and Transaction Model”.
InnoDBitablesiarrangeiyouridataionidiskitoioptimizeiqueriesibasedioniprimaryikeys.iEachiI
nnoDBitableihasiaiprimaryikeyiindexicalleditheiclusterediindexithatiorganizesitheidataitoim
inimizeiI/Oiforiprimaryikeyilookups.iSeeiSectioni15.6.2.1,i“ClusterediandiSecondaryiIndex
es”.

Toimaintainidataiintegrity,iInnoDBisupportsiFOREIGNiKEYiconstraints.iWithiforeignikeys
,iinserts,iupdates,iandideletesiareicheckeditoiensureitheyidoinotiresultiiniinconsistenciesiacr
ossirelateditables.iSeeiSectioni13.1.20.5,i“FOREIGNiKEYiConstraints”.
InnoDBiisiACID-
basediandisupportsicommitiandirollbackioperations.iMoreover,iitiisilessilikelyitoicrash,isoit
heiusers’idatairemainsiprotected.
Multi-useriperformanceiisipossibleidueitoirow-levelilocking.
SinceiInnoDBitablesiorganizeidataieffectively,iqueriesibasedioniprimaryikeysiareioptimized
.iThereiisiaiprimaryikeyiindexicalleditheiclusterediindexiinieachiInnoDBitable.iThisiindexia
rrangesitheidataitoireduceiI/Oiforiprimaryikeyiqueries.
MySQLiInnoDBisupportsiforeignikeyiconstraints,iwhichiallowsiachievingiandimaintainingi
dataiintegrity.
InnoDBicanialsoibeiusediwithitheiMariaDBiserver.iInithisicase,iInnoDBideliversiforeignike
ys,iXAitransactions,ianditransactionsiwithisavepoints.

InnoDBiCluster
Everyicompany’sipolicyipresupposesiprovidingitheisafestianditheimostistableidataiflow.iBu
tihowicaniitibeiachievediandiguaranteed?iTheiansweriliesiiniMySQLiInnoDBiCluster,iwhic
hioffersiaiconvenientisolutioniforiMySQL.iWithitheiinvolvementiofiAdminAPIiandiMySQ
LiShell,iyouicanieasilyimanageimultipleiMySQLiserveriinstancesitoiworkiasiaisingleiInnoD
BiCluster.
TheicomponentsiofiMySQLiInnoDBiClusteriincludeitheifollowing:
MySQLiRouteri(safeiroutingitoidatabaseinodes)
MySQLiGroupiReplicationi(multipleidatabaseiserversithatireplicateieachiother)
MySQLiShelli(aiconfigurationitooliforiMySQL,iwhichihelpsienableitopologiesiwithifaultito
lerance)
SeeihowiitialliworksitogetheriiniaisingleiInnoDBiCluster:
CreatingiInnoDBitables
IniorderitoicreateianiInnoDBitable,iyouisimplyispecifyiENGINEi=iInnoDBiiniyouriCREAT
EiTABLEistatement.iForiinstance:

CREATEiTABLEiEmp
i(
iiiiEmpIDiiiiSMALLINTiUNSIGNEDiNOTiNULL,
iiiiYearBorniYEARiNOTiNULL,
iiiiCityBorniVARCHAR(40)iNOTiNULLiDEFAULTi'Unknown'
i)
iENGINE=INNODB;

**************************************************************************

You might also like