Beruflich Dokumente
Kultur Dokumente
ClassroomUdacity
OptionalSQLiteTutorial
SinceSunshinewillbeusingaSQLitedatabasetostoreweatherdata,youshouldhaveabasicunderstandingofSQLiteanditscommandsbeforecontinuingthislesson.
ThisisanoptionalexerciseforanyonenewtoSQLdatabasesoranyoneinneedofarefresher.
Introduction
SQLiteisarelationaldatabasemanagementsystem,whichisanimplementationofSQL(StructuredQueryLanguage).ItcomespackagedwiththeAndroidOSasaC++
librarysothatappscanhaveprivatedatabases.SQLcanbeusedtocreate,searchandmaintaindatabases.Inthistutorial,youwilllearnaboutthesyntaxandusageof
SQLandseehowtocreateandmanageasmalldatabaseonyourcomputer.ThecommandsyoulearnherearesimilartotheSQLcommandsyouwillwriteforyour
Sunshineapp,inordertostoreandretrieveweatherdatafromaSQLitedatabase.
GetSQLite
1. DownloadtheSQLitecommandlineshellandinstall.Youcanfollowthistutorialorgodirectlytohttp://sqlite.org/download.html
2. Openterminalandnavigatetoafolderofyourchoicewhereyouwillsaveyourdatabase.Createanewdatabasefilecalledsunshine.dbandstarttheSQLiteshell
(whichwillrecognizeyourSQLcommands)bytyping:
sqlite3sunshine.db
3. Foralistofallcommands:
.help
4. Oneofthecommandsistolistoutalldatabases.Itshoulddisplayonedatabasecalledmainandthefilelocationonyourcomputerforsunshine.db.
.databases
Inanapp,youcanhavemultipledatabases.OurSunshineappwillonlyhaveasingledatabase,andthatdatabasecancontainmultipletables.
CreateADatabaseTable
1. Atableisacollectionofrowsandcolumnslikeaspreadsheet.UsetheCREATETABLEstatementtocreateanewdatabasetablecalledweather.Eachrowwillbe
onedaysworthofweatherdata.Itshouldhave6columnsofdata:ID,date,mintemperature,maxtemperature,humidity,andpressure.
IntheCREATETABLEstatement,eachcolumndefinitionisseparatedbycommas,whereyouprovidethecolumnnameanddatatypeforthatcolumn.Wealsospecify
thatthecolumnshouldbenonnull.Wespecifythe_idcolumntobetheprimarykeyanditsaninteger.
CREATETABLEweather(_idINTEGERPRIMARYKEY,dateTEXTNOTNULL,minREALNOTNULL,maxREALNOTNULL,humidityREALNOTNULL,pressureREALNOTNULL);
ThelistofpossibleSQLitedatatypesisausefulresource,oryoucanseethistutorial.
Note:SQLitekeywords,suchasCREATETABLEorPRIMARYKEY,arecapitalizedforeaseofreadabilitytodistinguishthemfromthetableandcolumnnamesthat
weveselected,butyoucanlowercasethekeywordsifyouwant.
Note:ThisisnotthefulltableyoullbeusinginSunshine,thisisjustasimplerversionofthetable.
2. Usethiscommandtolistoutalltables.Ensurethattheweathertablewascreated.
.tables
3. UseaSELECTstatementtoreturnoutallrowsintheweathertable.The*isasymbolthatmeansallofthecolumns.Atthistime,nothingwillbereturnedbecause
thetableiscreated,butthereisnodatainthetableyet.
SELECT*FROMweather;
4. Atanypoint,youcanfindouttheschemaofhowthetableswerecreatedinthedatabase
.schema
Insertrows
1. UseanINSERTstatementtoinsertanewrowofdataintotheweathertable.ThefollowingINSERTstatementinsertsarowintotheweathertableforJune25th,2014,
whichhadalowof16degrees,ahighof20degrees,0humidityand1029pressure.The_idofthisrowis1.
INSERTINTOweatherVALUES(1,'20140625',16,20,0,1029);
2. Queryforallrowsintheweathertable,andyoushouldseetheonerowofdatayoujustinserted.
SELECT*FROMweather;
https://www.udacity.com/course/viewer#!/cud853/l3621368730/m2602608541
1/3
12/29/2015
ClassroomUdacity
3. Tohavethecolumnnamebeprintedoutaswell(foreasierreadabilityastowhatvaluecorrespondstowhichcolumn),turntheheaderon.Thendothequeryagain.
.headeron
SELECT*FROMweather;
4. Experimentbyinsertinganother3rowsofdataintotheweather
Queryrows
1. PracticedoingquerieswhereyouprovideaselectionWHEREclausetonarrowdownthenumberofrowsthatarereturnedintheresult.Alwaysrememberthe
semicolonattheendofastatement!
ForallpossibleSQLiteoperators,seethislink.
Thisqueryreturnsrowsfromtheweathertablewherethedatecolumnexactlyequalsthe20140626.
SELECT*FROMweatherWHEREdate==20140626;
2. Thisqueryreturnsrowsfromtheweathertablewherethedatecolumnisbetween20140625and20140628.However,allcolumnsarenotreturned,wejustreturnthe
4specifiedcolumns(_id,date,min,andmax)oftherowsthatmatchthequery.
SELECT_id,date,min,maxFROMweatherWHEREdate>20140625ANDdate<20140628;
3. Thisqueryreturnsrowswheretheminimumtemperatureisgreaterthanorequalto18.Basedonthosematchingrows,weorderthembasedonincreasing(also
knownasascendingorASCforshort)maxtemperature.Thefirstrowoftheresultthatisprintedouttothecommandlinewillbetherow(withmintemperature>=
18)withmaxtemperaturethatislowestoutofallrows,sothatsubsequentrowswillhavehighermaxtemperature.
SELECT*FROMweatherWHEREmin>=18ORDERBYmaxASC;
Updaterows
1. YoucanalsoupdateexistingrowsinthedatabasewithanUPDATEstatement.Thisstatementupdatestheweathertablebysettingtheminimumtemperaturetobe0
andmaximumtemperaturetobe100forrowswherethedateisgreaterthan20140626butlessthan20140627.
UPDATEweatherSETmin=0,max=100wheredate>=20140626ANDdate<=20140627;
Whenyouprintoutthewholeweathertableagain,youcanseethat2rowswerechanged.
SELECT*FROMweather;
Deleterows
1. UseaDELETEstatementtodeleterowsfromadatabasetablethatmatchthegivenselectionclause.Inthiscase,wedeleteanyrowsfromtheweathertablewhere
humidityisnotequalto0.
DELETEFROMweatherWHEREhumidity!=0;
Addcolumns
1. Ifyouhavereleasedaversionofyourapptousers,andthendecideyouneedtochangethedatabaseschema,suchasaddingcolumns,thenyoullneedtoupgrade
yourdatabase.Youcanalterexistingtables,byusingtheALTERTABLEcommand.
Note:Ingeneral,youshouldntalteratabletoremoveacolumnbecauseyouredeletingdataandothertablescoulddependonthatcolumn.Insteadyoucanjustnull
outallvaluesinthatcolumn.
Thisstatementalterstheweathertablebyaddinganothercolumntothetablecalleddescription,whichwillalwaysbenonnullandcontaintext.Itwillalsodefaultto
thevalueSunnyifnovalueisprovided.Inreality,youwouldchooseamorereasonabledefault,butthisisjustforexamplepurposes.
ALTERTABLEweatherADDCOLUMNdescriptionTEXTNOTNULLDEFAULT'Sunny';
Verifythatthenewdescriptioncolumnexistswhenyouqueryallrowsandallcolumns.
SELECT*FROMweather;
Deletetable
1. DeletetheweathertablebyusingtheDROPTABLEcommand.Verifytherearenomoretablesinthedatabase.
https://www.udacity.com/course/viewer#!/cud853/l3621368730/m2602608541
2/3
12/29/2015
ClassroomUdacity
DROPTABLEweather;
.tables
Thesearejustthebasics.FeelfreetoplayaroundwithSQLitesomemore.Seethislink:http://www.sqlite.org/cli.html
Whenyouredone,enter .quit toexit,andyoucanmoveontothequizonthenextpage!
https://www.udacity.com/course/viewer#!/cud853/l3621368730/m2602608541
3/3