Tải bản đầy đủ - 0 (trang)
4 Inserting, Updating, and Deleting Data

4 Inserting, Updating, and Deleting Data

Tải bản đầy đủ - 0trang

wanttosupplydataforanattribute,youcanincludeNULL

insteadofavalue(aslongastheattributeisn'tdefinedasNOT

NULLandNULLisvalidforthatdatatype).Forexample,to

createapartialcustomerrow,youcoulduse:

INSERTINTOcustomerVALUES(1,'Williams','Lucy',NULL,3,

NULL,NULL,NULL,NULL,12,NULL,NULL);



TocreateanINSERTstatementusingthisfirstformat,youneed

toknowtheorderingoftheattributesinthetable.Youcan

discoverthetablestructurebytypingSHOWCOLUMNSFROM

customerintotheMySQLcommandinterpreterorbyreviewing

theCREATETABLEstatementusedtocreatethetable.TheSHOW

statementisdescribedindetailinChapter15.

Ifyouwanttoinsertmorethanonerow,youcanwritemore

thanoneINSERTstatement.Alternatively,youcanwriteone

INSERTstatementandseparateeachrowwithacomma.

Consideranexamplethatusesthelatterapproachandinserts

thedetailsfortwocustomers:

INSERTINTOcustomerVALUES(1,'Williams','Lucy','E',3,



'272StationSt','CarltonNorth','VIC','3054',12,'(613)83008460

'2002-07-02'),(2,'Williams','Selina','J',4,'12HothamSt',

'Collingwood','VIC','3066',12,'(613)99255432','1980-06-03');



ThisapproachisthefastestwaytoinsertdataintoMySQL.

Datacanalsobeinsertedusingasecondapproach.Consider



thisexample:

INSERTINTOcustomerSETcust_id=1,surname='Williams',

firstname='Lucy',initial='E',title_id=3,

address='272StationSt',city='CarltonNorth',

state='VIC',zipcode='3054',country_id=12,

phone='(613)83008460',birth_date='2002-07-10';



Inthisapproach,theattributenameislisted,followedbythe

assignmentoperator(=)andthenthevaluetobeassigned.This

approachdoesn'trequirethesamenumberofvaluesas

attributes,anditalsoallowsarbitraryorderingoftheattributes.

Thiscansaveyoulotsoftypingwhenarowhasmany

attributesbutissparselypopulatedwithvalues.Forexample,to

createapartialcustomerrow,youcoulduse:

INSERTINTOcustomerSETcust_id=653,surname='Williams',

firstname='Lucy',title_id=3,country_id=12;



Thefirstapproachcanactuallybevariedtofunctioninasimilar

waytothesecondbyincludingparenthesizedattributenames

beforetheVALUESkeyword.Forexample,youcancreatean

incompletecustomerrowwith:

INSERTINTOcustomer(cust_id,surname,city)

VALUES(1,'Williams','NorthCarlton');



Wheninsertingdata,non-numericattributesmustbeenclosed

ineithersingleordoublequotes.Ifastringcontainssingle

quotationmarks,thestringcanbeenclosedindoublequotation

marks.Forexample,considerthestring"SteveO'Dwyer".

Likewise,stringscontainingdoublequotationmarkscanbe

enclosedinsinglequotationmarks.Analternativeapproachis

toescapethequotationcharacterbyusingabackslash

character;forexample,asinthestring`SteveO\'Dwyer'.

Numericvaluescanalsobeenclosedinquotesbuttheyaren't

mandatory.

Thereareotherwaystoinsertdatainadditiontothose

discussedhere.Forexample,apopularvariationistoinsert

datafromanothertableusingaqueryortoinsertdatafroma

formattedtextfile.Thesetwoapproachesandothervariants

arediscussedinChapter15.



5.4.1.1Defaults

Ifyoudon'tincludethevalueforanattribute,itissettothe

DEFAULTvalueifit'ssuppliedinthetabledefinitionortoNULL

otherwise(ifitisvalidfortheattributetobeNULL).Ifan

attributeisdefinedasbeingNOTNULLanddoesnothavea

DEFAULTvalue,thevaluethat'ssetdependsontheattribute

type;forexample,integerattributesaresetto0(whichcauses

anauto_incrementattributetobepopulatedwithanew

identifier,asdiscussednext)andstringstotheemptystring.

However,ratherthanworryaboutwhathappens,we

recommendthatyoudefineaDEFAULTvalueforanyattribute

thatyoudon'talwayswanttolistinanINSERTstatement.Even

ifyouwantNULLtobeinsertedwhennothingisprovided,you

candefineitastheDEFAULT.



InsertingNULLintoaTIMESTAMP(oranydateortimetype)

attributestoresthecurrentdateandtime.Inserting0intoa

TIMESTAMPattributedoesn'thavethesameeffectasinserting

NULL,because0isavaliddateandtimecombination.



5.4.1.2Auto-increment

MySQLprovidesanon-standardSQLauto_incrementmodifier

thatmakesmanagementofprimarykeyseasy;mostother

databaseserversprovideasimilarnon-standardfeature.The

goalofusingauto_incrementistomakesurethateachrowin

yourtablehasauniqueprimarykeysothatyoucanrefertoit

inothertables;asdiscussedpreviously,thisisacommon

requirementindatabases.

Thefollowingisasimpletabledefinitionthatusesthe

auto_incrementfeaturetocreateauniquevalueforthe

primarykey:

CREATETABLEnames(

idsmallint(4)NOTNULLauto_increment,

namevarchar(20),

PRIMARYKEY(id)

);



Youcaninsertdataintothistablebysettingonlythename

attribute:

INSERTINTOnamesSETname="Bob";



Inthisexample,theidissettothenextavailableidentifier

becausethedefaultvalueofanintegerattributeis0andthis

invokestheauto_incrementfeature.

Ingeneral,whenyouinsertNULL(orzero)asthenextvaluefor

anattributewiththeauto_incrementmodifier,thevaluethatis

storedisthemaximumvalue+1.Forexample,ifthereare

already10rowsinthenamestablewithidvaluesof1to10,

insertingarowwithNULLastheid(ornotprovidinganidand

invokingthedefaultbehavior)createsarowwithanidvalueof

11.

Theauto_incrementmodifierisausefulfeaturewhenyouwant

toinsertdatawithauniqueprimarykey,butdon'twanttohave

toreadthedatafirsttodeterminethenextavailablevalueto

use.AsweshowyoulaterinChapter8,thisalsohelpsavoid

concurrencyproblems(and,therefore,theneedforlocking)

whenseveralusersareusingthesamedatabase.The

disadvantageisthatit'saproprietaryMySQLfeature.However,

wealsoshowyouhowtodevelopagenericapproachto

managingidentifiersinChapter9andwealsoshowyouhowit's

donewithPHP'sPEARDB.

Onlyoneattributeinatablecanhavetheauto_increment

modifier.

Theresultofanauto_incrementmodifiercanbecheckedwith

theMySQL-specificfunctionlast_insert_id().Fortheprevious

example,youcancheckwhichidwascreatedwiththe

statement:

SELECTlast_insert_id();



Thisstatementreports:

+------------------+

|last_insert_id()|

+------------------+

|11|

+------------------+

1rowinset(0.04sec)



Youcanseethatthenewrowhasid=11.Tocheckanidentifier

value,thefunctionshouldbecalledimmediatelyafterinserting

thenewrow.



5.4.2DeletingData

TheDELETEstatementremovesdatafromtables.Forexample,

thefollowingdeletesalldatainthecustomertablebutdoesn't

removethetable:

DELETEFROMcustomer;



ADELETEstatementwithaWHEREclausecanremovespecific

rows;WHEREclausesarefrequentlyusedinquerying,andthey

areexplainedlaterinSection5.5.Considerasimpleexample:

DELETEFROMcustomerWHEREcust_id=1;



Thisdeletesthecustomerwithacust_idvalueof1.Consider

anotherexample:

DELETEFROMcustomerWHEREsurname='Smith';



Thisremovesallrowsforcustomerswithasurnamevalueof

Smith.



5.4.3UpdatingData

DatacanbeupdatedusingasimilarsyntaxtotheINSERT

statement.Consideranexample:

UPDATEcustomerSETstate=upper(state);



Thisreplacesthestringvaluesofallstateattributeswiththe

samestringinuppercase.Thefunctionupper()isoneofmany

MySQLfunctionsdiscussedinChapter15.

Youcanupdatemorethanoneattributeinastatement.For

example,tosetboththestateandcitytouppercase,use:

UPDATEcustomerSETstate=upper(state),city=upper(city);



TheUPDATEstatementisalsooftenusedwiththeWHEREclause.

Forexample:

UPDATEcustomerSETsurname='Smith'WHEREcust_id=7;



Thisupdatesthesurnameattributeofcustomer#7.Considera

secondexample:

UPDATEcustomerSETzipcode='3001'WHEREcity='Melbourne';



Thisupdatesthezipcodeofallrowswithacityvalue

Melbourne.

AfteranUPDATEiscompleted,MySQLreturnsthenumberof

rowsthatwerechanged.IfMySQLfindsthatavaluedoesn't

needtobechanged(becauseit'salreadysettothevalueyou

wanttochangeitto),itisn'tupdatedandisn'tincludedinthe

countthat'sreturned.



5.5QueryingwithSQLSELECT

TheSELECTstatementisusedtoqueryandretrieveoneor

morerowsfromadatabase.Weintroduceitinthissection,and

thenshowyoutheWHEREclauseforselectingdatathatmatches

acondition.Thesectionconcludeswithanintroductiontothe

moreadvancedfeaturesofSELECTstatementsandashortcase

study.



5.5.1BasicQuerying

ConsideranexampleSELECTstatement:

SELECTsurname,firstnameFROMcustomer;



Thisoutputsthevaluesoftheattributessurnameand

firstnamefromallrowsinthecustomertable.Assumingwe

previouslyinsertedfourrowswhenwecreatedthewinestore

database,theoutputfromtheMySQLcommandinterpreteris:

+-----------+-----------+

|surname|firstname|

+-----------+-----------+

|Marzalla|Dimitria|

|LaTrobe|Anthony|

|Fong|Nicholas|



|Stribling|James|

+-----------+-----------+

4rowsinset(0.04sec)



AnyattributesofatablemaybelistedinaSELECTstatementby

separatingthemwithacomma.Ifallattributesarerequired,

theshortcutofanasteriskcharacter(*)canbeused.Consider

thestatement:

SELECT*FROMregion;



Thisoutputsallthedatafromthetableregion:

+-----------+---------------------+

|region_id|region_name|

+-----------+---------------------+

|1|All|

|2|GoulburnValley|

|3|Rutherglen|

|4|Coonawarra|

|5|UpperHunterValley|

|6|LowerHunterValley|



|7|BarossaValley|

|8|Riverland|

|9|MargaretRiver|

|10|SwanValley|

+-----------+---------------------+

10rowsinset(0.01sec)



SELECTstatementscanalsooutputdatathatisn'tfroma

database.Considerthefollowingexample:

SELECTcurtime();



Thisexamplerunsafunctionthatdisplaysthecurrenttime:

+-----------+

|curtime()|

+-----------+

|08:41:50|

+-----------+

1rowinset(0.02sec)



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

4 Inserting, Updating, and Deleting Data

Tải bản đầy đủ ngay(0 tr)

×