Getting Started with SQLite
Copyright2021BostonUniversity.AllRightsReserve d.
AuthoredbyWarrenMansur.
Table of Contents
Introduction..............................................................................................................................3
SQLite Overview......................................................................................................................3
Supported Platforms..............................................................................................................3
Downloading and Installing DB Browser for SQLite...................................................4
Step 1: Downloading DB Browser for SQLite...........................................................4
Step 2: Installing DB Browser for SQLite..................................................................5
Creating Your First Table....................................................................................................10
Step 1: Launching DB Browser for SQLite..............................................................10
Step 2: Create a New Database.................................................................................11
Step 3: Adding a Table..................................................................................................16
Downloading the JDBC Driver..........................................................................................20
Connecting to your Database in Eclipse....................................................................... 22
Step 1: Creating a New Project..................................................................................22
Step 2: Adding the JDBC Driver.................................................................................23
Step 3: Inserting Rows.................................................................................................. 29
Connecting to your Database in IntelliJ........................................................................32
Step 1: Creating a New Project..................................................................................32
Step 2: Adding the JDBC Driver.................................................................................35
Step 3: Inserting Rows.................................................................................................. 38
Next Steps...............................................................................................................................41
Appendix A: Source Code..................................................................................................42
Works Cited.............................................................................................................................43
Page3of43
Introduction
ThisSQLitegettingstartedguideisusedbystudentsenrolledintheMasterofScienceinSoftwareDevelopmentand
otherComputerScienceDepartmentprogramsinbothoncampusandonlineprograms.Thedocumentdescribes
SQLite,connectingtoSQLiteinEclipseandIntelliJ,andworkingwithyourfirsttable.Notethatasnewversionsof
SQLitearereleased,someofthescreensmaylookdifferentthanthescreenshotsinthisdocument.Nevertheless,
thisguidewillhelpgetyoustartedquicklyonanymodernversionofversionofSQLServerExpress.
Whyislearningaboutdatabasesimportant?Mostseriousapplicationshavetheneedfordurablestorage,thatis,
storinginformationforanextendedperiodoftime.Whilestoringinformationinfilessatisfiestheneedsforsome
applications,manyrequireuseofadatabase.Databasessupportfoursignificantfeaturesnotsupportedwellbyfile
systemsefficientdataaccessamongstlargesetsofdata,extremelygranularsecurity,highlystandardized,cross
platformAPIs,andstructuralindependence.Databasessupportretrievinginformationquickly,oftentimeslessthan
asecond,fromvastamountsofdata.Databasessupportsecurityevendowntoindividualfieldsinanextensible
manner.DatabaseshavehighlystandardizedAPIsforcrossplatformaccess.Lastly,applicationsthatusedatabases
arenotdependentuponanyparticularfilesystemorfilestructure.Databasesprovidefeaturesneededbymany
seriousapplications.
Relationaldatabasesarebyfarthemostuseddatabasesintheworld.Estimatesputworldwideusageatabout77%
relational,and23%NoSQL/Search(SolidIT).Whendatamustbesharedacrossmanyclientsand/orserversofan
application,serverbaseddatabasesareutilized,themostpopularbeingOracle,SQLServer,MySQL,andPostgres
(SolidIT).Whendatadoesnotneedtobesharedortheneedforsharingisverylimited,embeddeddatabasescan
beutilized,themostpopularbyfarbeingSQLite(SolidIT).
Ifyoucan’tdeterminehowtoproceedorsomethinggoeswrong,andwebsearchesdon’thelp,askyourfacilitator
orinstructorforhelp.Goodluck,andhavefun!
SQLite Overview
SQLiteisthemostused,embedded(serverless)relationaldatabaseintheworld.Itisopensourceandfreetouse.
UnlikeserverbaseddatabaseslikeOracleandSQLServer,SQLiterunsentirelyintheapplicationthatusesit,and
storesallofitsdurableobjectsinasinglediskfile.SQLitecanbeusedacrossallmajorplatforms,whichmeansthe
databasefilecanbefreelycopiedandusedacrossdeviceswithdifferencearchitectures.SQLiteisidealfor
applicationsthatwouldtraditionallyusefilestostoredata,givingthemaccesstothepowerofarelationaldatabase
withouttheexpenseandoverheadofinstallingandmaintainingaserverbaseddatabase(SQLite).
AlthoughSQLiteisnotareplacementforOracle,SQLServer,orPostgres,thegoodnewsis,onceyoulearntoaccess
anduseanyonemodernrelationaldatabase,youcanusetheotherswithoutmuchadditionaleffort.Allmodern
relationaldatabasesutilizetheStructuredQueryLanguage(SQL)fordataaccessandmanipulation.SQLishighly
standardizedacrossdatabases.Althoughtherearesomedifferences,thesignificantaspectsarethesameacross
databases.Inaddition,JavasupportsastandardizedAPI,JDBC,foraccessinganydatabase.ConnectivityfromJava
doesnotdiffermuchbetweendatabases.ThusSQLiteisanexcellentfirstdatabaseforJavadevelopers,becausethe
intricaciesofrelationaldatabasesandconnectivitycanbelearnedwithouttheoverheadofdatabaseinstallation,yet
SQLiteisusedinseriousapplicationsworldwide.
Supported Platforms
SQLitesupportsallmajorplatforms.IfyouareusingWindows,aMac,Linux,anAndroidphone,aniPhone,andsome
otheroperatingsystems,youcanuseSQLite.Forthesakeofbrevity,theexamplesandscreenshotsinthisdocument
arefortheMicrosoftWindowsfamily,includingWindows8andWindows10.However,pleasekeepinmindyoucan
followthesamestepsforotheroperatingsystems;yourscreensmaylookalittledifferent,butalmostallofthe
stepsarethesame.
Page4of43
Downloading and Installing DB Browser for SQLite
Itisabestpracticetomanageyourdatabase’sstructurewithaSQLclient.Typically,weuseaSQLclienttofirstadd
thetables,indexes,andtriggers(ifneeded),aswellasanyinitialdata.Thenwhenourapplicationexecutes,itwill
add,modify,andremovedataasneeded,butnotmodifythestructureofthetablesandindexes.Byseparating
structuremanipulationfromdatamanipulation,wecancarefullyapplygooddatabasedesignprinciples,andavoid
embeddingtablestructureinourapplication.
ApopularSQLclientforSQLiteisDBBrowserforSQLite.Thissectionhasyouinstalltheclientanduseittocreatean
initialtable.
Step 1: Downloading DB Browser for SQLite
Visit Website
Gotohttps://sqlitebrowser.org/dl/togetstarteddownloadingDBBrowserforSQLite.The
websiteisregularlyupdated,sowhatyouseemaybedifferentthanthefollowing.
Download
Clickthe“Standardinstallerfor64bitWindows”undertheWindows
downloadstostartthedownload.Ifyouareusingadifferentoperating
system,downloadtheappropriateinstaller.
Page5of43
Step 2: Installing DB Browser for SQLite
Execute
Installer
Yourbrowserwillnowgiveyoutheoptiontoruntheexecutableit
downloaded.Goaheadandrunit.You’llseeascreenlikethefollowing.
Accept
License
Agreement
AfterclickingtheNextbutton,theinstallerwillaskyoutoacceptthelicenseagreement.
Page6of43
Select DB
Browser
Options
AfterclickingtheNextbutton,you’llbeaskedwhatyouwouldliketoinstall.Selectboth
the“Desktop”and“ProgramMenu”optionsunder“DBBrowser(SQLite)”.
Page7of43
Accept
Defaults
AfterclickingtheNextbutton,you’llbeaskedifyou’dliketochangeany
installoptions.Youdon’tneedtochangeanythingonthisscreen.

Page8of43
Start the
Install
AfterclickingtheNextbutton,you’llbepresentedwithascreenthatasks
youtoinstall.Goaheadandclickthe“Install”button.

You’llseeaprogressscreenfirst.
Page9of43
Thenyou’llseeascreenindicatingtheinstallwassuccessful.
GoaheadandclicktheFinishbutton.Congratulations!DBBrowserforSQLiteisinstalled
onyourmachine.
Page10of43
Creating Your First Table
Togetyoustarted,we’llwalkyouthroughcreatingyourfirsttableinthissection.Thetablewillbenamed“Person”
andwillstorebasicinformationaboutpeople.Inalatersectionwe’llhaveyouconnecttoyourdatabaseandstart
workingwithdatainthetable.
Step 1: Launching DB Browser for SQLite
Launch from
Windows
YoucanlaunchDBBrowserforSQLitefromWindows,eitherfromtheStartMenu,or
fromtheshortcutonthedesktop,asshowninthebelowscreenshots.
StartMenu
Desktop
Page11of43
Step 2: Create a New Database
ThefirstthingyouneedtodoafterlaunchingtheapplicationiscreateaSQLitedatabase,whichwillhousethetables
andotherobjectsyouwanttoworkwith.
Click New
Database
Togetstarted,clickthe“NewDatabase”buttoninthetopleft,asshownbelow.
Determine
Path
Nowyouneedtochooseafolderandfilename.Itmaybenecessarytocreateafolderto
keepthedatabaseinaplaceyoucanremember.
Inourexample,wehavecreated“C:\SQLite”asthefolder,becauseitisacommon
locationthatiseasytoremember.Laterwhenyou’redevelopingwithinthecontextof
yourapplication,youmightchoosetosaveyourdatabaseaspartofyourJavaproject.In
therealworld,thedatabaseiscommonlysavedinitsownsubdirectoryinasourcecode
repositoryfortheproject.
Weentered“GettingStarted.db”asthefilename.The“GettingStarted”namehelpsus
knowit’sforthisgettingstartedtutorial.The“.db”fileextensionisoneoftheaccepted
extensionsforSQLitefiles.Thereareafewotheracceptedextensionsaswell;however,
“.db”appearstobethemostcommon.
Page12of43
Thisisshowninthescreenshotbelow.
Close Table
Definition
Screen
Immediatelyafterclickingthe“Save”buttontocreatethedatabase,awindowpopsup
thatletsusdefinetablesusingawizard.
Simplyclosethiswindow,aswewillbetypinginSQLdirectly.
Page13of43
Select
Execute SQL
Tab
WewanttotypetheCREATETABLEcommandinSQL,soweneedtoclickonthe
“ExecuteSQL”tabfirst,asshownbelow.
Create Table
Next,wetypethecommandtocreatethetable.Typethiscommandexactly:
CREATE TABLE Person (
person_id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name VARCHAR(64) NOT NULL,
last_name VARCHAR(64) NOT NULL,
birth_date DATE NOT NULL);
Thisisshownbelow.
Thiscommandcreatesatablenamed“Person”withaperson_idautoincrementingfield,
firstandlastnamefields,andabirthdatefield.
Page14of43
Nextclickthe“Executeall/selectedSQL”button,whichlookslike .Afteryouhavedone
so,amessagewillappearstatingthatthetablehasbeencreated.Thisisallshown
below.
Youcanseethatyourpersontablewassuccessfullycreated!
Save Changes
Inordertosavethechangestothedatabasefile,youneedtoclickthe“WriteChanges”
button,asshownbelow.
Page15of43
Onceyouhavedoneso,thebuttonwillgrayout,indicatingthereisnothingmoreto
save.
Youcandetermineifanychangesneedtobesavedbylookingatthesebuttonstoseeif
theyareclickable,orgrayedout.
Database
Ready for
Application
Congratulations!You’vecreatedaSQLitedatabaseandaddedatabletoit.Thedatabase
isnowreadyforanapplicationtoconnecttoitandworkwithpersondata,whichwe’ll
dointhenextsection.
Page16of43
Step 3: Adding a Table
Close Table
Definition
Screen
Immediatelyafterclickingthe“Save”buttontocreatethedatabase,awindowpopsup
thatletsusdefinetablesusingawizard.
Simplyclosethiswindow,aswewillbetypinginSQLdirectly.
Select
Execute SQL
Tab
WewanttotypetheCREATETABLEcommandinSQL,soweneedtoclickonthe
“ExecuteSQL”tabfirst,asshownbelow.
Page17of43
Create Table
Next,wetypethecommandtocreatethetable.Typethiscommandexactly:
CREATE TABLE Person (
person_id INTEGER PRIMARY KEY AUTOINCREMENT,
first_name VARCHAR(64) NOT NULL,
last_name VARCHAR(64) NOT NULL,
birth_date DATE NOT NULL);
Thisisshownbelow.
Thiscommandcreatesatablenamed“Person”withaperson_idautoincrementingfield,
firstandlastnamefields,andabirthdatefield.
Page18of43
Nextclickthe“Executeall/selectedSQL”button,whichlookslike .Afteryouhavedone
so,amessagewillappearstatingthatthetablehasbeencreated.Thisisallshown
below.
Youcanseethatyourpersontablewassuccessfullycreated!
Save Changes
Inordertosavethechangestothedatabasefile,youneedtoclickthe“WriteChanges”
button,asshownbelow.
Page19of43
Onceyouhavedoneso,thebuttonwillgrayout,indicatingthereisnothingmoreto
save.
Youcandetermineifanychangesneedtobesavedbylookingatthesebuttonstoseeif
theyareclickable,orgrayedout.
Database
Ready for
Application
Congratulations!You’vecreatedaSQLitedatabaseandaddedatabletoit.Thedatabase
isnowreadyforanapplicationtoconnecttoitandworkwithpersondata,whichwe’ll
dointhenextsection.
Page20of43
Downloading the JDBC Driver
Withyourdatabasesetup,thenextstepistodownloadtheSQLiteJDBCdriversothatitcanbeimportedintoyour
Eclipse,IntelliJ,orotherIDEproject.JavarequirestheJDBCdrivertoaccessthedatabase.
Visit the
Website
Togetstarted,visithttps://github.com/xerial/sqlitejdbc/releases.Youwillseealistofdrivers
there,similartothebelowscreenshot.
Page21of43
Download
Driver
Tostartthedownload,clickonthelinkfortheJarfileforthemostrecentversionavailable.You
don’tneedthesourcefiles,justthejarfile.AnexampleJarfilelinkisshownbelow.
Onceclicked,yourbrowserwillaskyouwhereyou’dliketosavethefile.Makesuretosavethe
driverinadirectoryyoucanremember,becauseinalatersectionwewillbrowsetothe
directorytousethedriverinourIDE.
Intheexamplebelow,itissavedintotheC:\SQLite\Driverdirectory,onesubdirectorybelow
wherethedatabaseitselfisstored.
Oncedownloaded,youaresettoimportitintoEclipse,IntelliJ,oryourotherIDE,andmay
continuewiththenextsectionthatappliestoyou.
Page22of43
Connecting to your Database in Eclipse
WiththedatabasesetupandtheJDBCdriverdownloaded,thenextstepistousethedatabaseinyourJavacode.To
getyoustartedwithSQLite,wewillexploreconnectingtoyourdatabase,addingdataintothealreadycreated
Persontable,andqueryingthePersontable.
ThissectionillustrateshowtodosoinEclipse.IfyouareusingIntelliJ,youmayskipthissectionandproceedwith
thenextsectiontitled“ConnectingtoyourDatabaseinIntelliJ”.
Step 1: Creating a New Project
Identify
Project
YoucancreateanewJavaprojectwhichwillbeusedtotestyourdatabaseconnection.Or,if
youalreadyhaveaproject,youcanusethatandskiptoStep2.Thefirststepistoinitiate
creationwithFile/New/JavaProject,asshownbelow.
Name Project
Wenameourproject“Database”sincewewillbetestingoutusingourdatabase.
Oncethenameisgiven,clickthe“Finish”button.
Page23of43
NowourprojectshowsupunderPackageExplorer.
Step 2: Adding the JDBC Driver
Add JDBC
Driver Jar
RightclickonyourprojectinPackageExplorer,thenclickonBuildPath/AddLibraries...
Page24of43
Select“UserLibrary”andclickNext.
Clickthe“UserLibraries...”button.
Page25of43
Click“New...”.
Giveitaname.Hereweusethename“Database”.
Page26of43
Click“AddExternalJar...”.
BrowsetothelocationoftheJarfileyouextractedandselectthefile.Wehadputitinto
C:\SQLite\Driverbelow.
Onceyou’veselectedtheJar,youshouldseesomethinglikethis,showingthattheSQLite
JDBCjarhasbeenaddedtothelibrary.
Page27of43
Click“ApplyandClose”toapplywhatyouhavedone.
Onthenextscreen,makesurethe“Database”userlibraryisselected,andclickthe
“Finish”button.
Page28of43
InPackageExplorer,youwillnowseethattheSQLitejarhasbeenaddedtoyourproject.
Notethatinthisprocessweaddedan“External”jarbecausethejarresidedina
directoryoutsideofourprojectdirectory.YoucouldalsocopytheJarintoyourprojectif
you’dlikeanduseitasaninternaljar.Itwillworkeitherway.
Inrealworldsituations,someorganizationshaveacommonJardirectorycheckedintoa
repositorythatcanbesharedbymanyprojects,justlikewehavedoneherewiththe
C:\SQLite\Driverdirectory.SomeorganizationsputtheJarsintoeachproject.Yetother
organizationsusearobustJarmanagementtoolsuchasIvy,whichstorestheJarsona
server,andareretrieveddynamicallybythebuildprocess.Theimportanttakeawayhere
isthattheSQLitejarmustbeincludedinyourproject,whereveritmaybelocated.
Page29of43
Step 3: Inserting Rows
Create Class
NowyoucreateaJavaclassthatconnectstoyourdatabase,insertstworows,thenqueriesthose
rows,outputtingtheresultstothescreen.Theentireclassisbelow.
First,let’sstartwithahighlevelsummary.Themainmethodopensaconnection,andpassesitto
aninsertmethodandquerymethod,respectively.Theinsertmethodinsertstworowsintothe
Persontable.Thequerymethodretrievesthoserowsandprintsthemoutinatabularformat.
Althoughtherearemanylines,weexplaineachlineinturn.Notethatwedonotdescribethe
linessequentially;rather,wedescribethemintermsofprogramflow(whichstartsinthemain
method).
Line1 Weputthisclassintoa“database”package.
Line2 Weimportthejava.sqlpackagebecausewemakeuseofmanyofitsclasses.
Line32 Westartthemainmethodbydefiningtheconnectionstringforourdatabase.
The“jdbc:sqlite”portioninstructstheJDBCAPItousetheSQLitedriverwe
includedinourproject,asopposedtosomeotherdriversuchasOracleorSQL
Server,the“C:/SQLite/GettingStarted.db”portioninstructstheSQLiteJDBC
driverastowhatfiletoopen.Sincewehadsavedourdatabasefileto
Page30of43
C:\SQLite\GettingStarted.db,wespecifythatintheconnectionstring.Although
thestringmaylookterse,theinformationinitiseasilyunderstandable.
Line33 Thisopenstheconnectiontoourdatabase,insideofatry/withblockwhichwill
automaticallycloseit.Inordertoworkwiththedatabaseinourapplication,a
connectionmustbeopentothedatabase.
Line35 Thisinvokesourinsertmethodwhichwillinserttherowsintoourdatabase.
Line6 Insidetheinsertmethod,thisisanexampleofSQLembeddedintoour
application.ThisINSERTINTOcommandisusedastheinstructiontoinsertarow
intothePersontable.The“(first_name,last_name,birth_date)”portion
describeswhichcolumnsweareinsertinginto,andtheorderwhichwespecify
them.Inthiscase,weareinsertingintothefirst_name,last_name,and
birth_datecolumns,respectively.Notethatbecauseperson_idisan
autoincrementingfield,wedon’tspecifythathere.Thedatabasewill
automaticallyassignitavalue.The“VALUES(?,?,?)”portionindicatesthatwe
areinsertingparameterizedvalues,asopposedtohardcodingvalues.Weusethe
“?”toindicatethatwearenothardcodinganyvalue,butcanchangethevalueat
runtime.
Line7 WeinstantiateaPreparedStatement,whichisneededtoexecutethe
parameterizedSQL.BypassingtheSQLstringasanargument,wehavetoldthe
JDBCdriverwhichSQLcommandwewantittoexecute.Weputthisinstantiation
insideoftry/withblocksothatitwillbeclosedautomatically.
Lines810 Herewedefinewhattheparameters(definedbythe“?”intheSQLstring)arein
turn.Thefirstparameteris“Bob”correspondingtothefirst_namecolumn,the
secondparameteris“Smith”,correspondingtothelast_namecolumn,andthe
thirdparameteris1/13/1976,correspondingtothebirth_datecolumn.
Line11 ThisinstructstheJDBCdrivertoexecutethepreparedstatementwiththegiven
parameters.Withtheparametersset,itwillbeexecutingthiscommand(butstill
usingparametersbehindthescenes):
INSERT INTO Person(first_name, last_name, birth_date)
VALUES (‘Bob’, ‘Smith’, ‘1/13/1976’)
Lines1316Followingsimilarlogictolines811,theselinesinsertanewrowwithfirst_name
=“Jane”,last_name=“Elizabeth”,andbirth_date=“3/15/1979”.
Line35 Thisinvokesourquerymethodwhichwillretrieveanddisplaytherowswehave
inserted.
Line21 Insidethequerymethod,thisSQLstringistoselectallfourcolumnsfromthe
Persontable,inthisorderperson_id,first_name,last_name,birth_date.
Lines2223Astatementiscreatedonline22withtheconn.createStatement()method,and
online23thequery(previouslydefinedonline21)isexecutedwiththe
stmt.executeQuery()method.ThisreturnsanobjectoftypeResultSet,whichhas
allrowsandcolumnsfromtheresults.Thesearecreatedwithinatry/withblock
sothattheyareautomaticallyclosed.
Line24 Thiswhileloopusesthers.next()methodtoiteratethrougheachrow.Aslongas
thereisanotherrowintheresultset,thenext()methodwillreturntrue.
Page31of43
Lines2526Thisprintsouttheresultsofthequeryinatabularformat.Notethatthe
ResultSetclassprovidesmethodssuchasgetString(),getDate(),andgetInt(),to
retrievethespecificfieldsinarow.Thecorrectmethodmustbeusedforthe
correctdatatype.Forexample,getInt()mustbeusedforperson_idsinceitisan
integer,andgetDate()mustbeusedforbirth_datesinceitisadate.Thefirst
argumentofthesemethodsisthecolumnnumber.Forexample,thegetInt()call
specifies“1”asthecolumnnumbersinceperson_idisqueriedfirst.The
getDate()callspecifies“4”asthecolumnnumberisbirth_dateisqueriedlast.
NOTE:ThesourcecodeisavailableinAppendixAsothatyoumaycopyandpasteasneeded.
Run Class
Withtheclassdefined,wecannowrunitwiththeRun/Runmenucommand.
Aftertheclassexecutes,youseetheoutputasbelow.
Noticethattheperson_idautoincrementcolumnstartsat1andincrementsupwardsby1.
FurthernoticethatBobSmithbornon1/13/1976islistedfirst,followedbyJaneElizabethbornon
3/15/1979.
Page32of43
Connecting to your Database in IntelliJ
WiththedatabasesetupandtheJDBCdriverdownloaded,thenextstepistousethedatabaseinyourJavacode.To
getyoustartedwithSQLite,wewillexploreconnectingtoyourdatabase,addingdataintothealreadycreated
Persontable,andqueryingthePersontable.
ThissectionillustrateshowtodosoinIntelliJ.IfyouareusingEclipse,youmayskipthissectionandproceedwith
thepriorsectiontitled“ConnectingtoyourDatabaseinEclipse”.
Step 1: Creating a New Project
Create a
Project
Clickthe“CreateNewProject”optiontogetstartedcreatingyourproject.
Page33of43
Choose
Project Type
Yournextstepistochoosethe“Java”projecttype.Thereareothertypesofprojectsyoucan
create,butatypicalprojectisaJavaprojectwhichallowsyoutypeJavacodeandexecuteit.
TheJavaprojecttypeisselectedbydefault,sojustclicktheNextbuttonto
continue.
Accept
Template
Defaults
Next,thescreenpromptsyoutodecidewhetheryou’recreatingyourprojectfroma
templateornot.Wearecreatingaprojectfromscratch(whichistypical),soleavethe
“Createfromprojecttemplate”checkboxuncheckedandclicktheNextbutton.
Page34of43
Name Project
Wenameourproject“Database”sincewewillbetestingoutusingourdatabase.
Oncethenameisgiven,clickthe“Finish”button.
NowourprojectshowsupintheProjectwindow.
Page35of43
Step 2: Adding the JDBC Driver
Add JDBC
Driver Jar
StartbyaccessingtheFile/ProjectStructuremenuoption.
Onthenewwindowthatappears,clickontheModuleoption,thentheDependencies
tab,asshownbelow.
Page36of43
Thenclickontheplussign,,thenclickon“JARsordirectories”,asshownbelow.
Fromthere,selectthedriverthatwasdownloadedintheC:\SQLite\Driverdirectory,and
clicktheOKbutton.
You’llnowseethejarfileincluded.ClicktheOKbuttontocloseoutoftheProject
Structurewindow.
Page37of43
UndertheExternalLibrariesontheProjectwindow,you’llseethejaraswell.
Notethatinthisprocessweaddedan“External”jarbecausethejarresidedina
directoryoutsideofourprojectdirectory.YoucouldalsocopytheJarintoyourprojectif
you’dlikeanduseitasaninternaljar.Itwillworkeitherway.
Inrealworldsituations,someorganizationshaveacommonJardirectorycheckedintoa
repositorythatcanbesharedbymanyprojects,justlikewehavedoneherewiththe
C:\SQLite\Driverdirectory.SomeorganizationsputtheJarsintoeachproject.Yetother
organizationsusearobustJarmanagementtoolsuchasIvy,whichstorestheJarsona
server,andareretrieveddynamicallybythebuildprocess.Theimportanttakeawayhere
isthattheSQLitejarmustbeincludedinyourproject,whereveritmaybelocated.
Page38of43
Step 3: Inserting Rows
Create Class
NowyoucreateaJavaclassthatconnectstoyourdatabase,insertstworows,thenqueriesthose
rows,outputtingtheresultstothescreen.Theentireclassisbelow.
First,let’sstartwithahighlevelsummary.Themainmethodopensaconnection,andpassesitto
aninsertmethodandquerymethod,respectively.Theinsertmethodinsertstworowsintothe
Persontable.Thequerymethodretrievesthoserowsandprintsthemoutinatabularformat.
Althoughtherearemanylines,weexplaineachlineinturn.Notethatwedonotdescribethelines
sequentially;rather,wedescribethemintermsofprogramflow(whichstartsinthemainmethod).
Line1 Weputthisclassintoa“database”package.
Line2 Weimportthejava.sqlpackagebecausewemakeuseofmanyofitsclasses.
Line32 Westartthemainmethodbydefiningtheconnectionstringforourdatabase.
The“jdbc:sqlite”portioninstructstheJDBCAPItousetheSQLitedriverwe
includedinourproject,asopposedtosomeotherdriversuchasOracleorSQL
Server,the“C:/SQLite/GettingStarted.db”portioninstructstheSQLiteJDBC
Page39of43
driverastowhatfiletoopen.Sincewehadsavedourdatabasefileto
C:\SQLite\GettingStarted.db,wespecifythatintheconnectionstring.Although
thestringmaylookterse,theinformationinitiseasilyunderstandable.
Line33 Thisopenstheconnectiontoourdatabase,insideofatry/withblockwhichwill
automaticallycloseit.Inordertoworkwiththedatabaseinourapplication,a
connectionmustbeopentothedatabase.
Line35 Thisinvokesourinsertmethodwhichwillinserttherowsintoourdatabase.
Line6 Insidetheinsertmethod,thisisanexampleofSQLembeddedintoour
application.ThisINSERTINTOcommandisusedastheinstructiontoinsertarow
intothePersontable.The“(first_name,last_name,birth_date)”portion
describeswhichcolumnsweareinsertinginto,andtheorderwhichwespecify
them.Inthiscase,weareinsertingintothefirst_name,last_name,and
birth_datecolumns,respectively.Notethatbecauseperson_idisan
autoincrementingfield,wedon’tspecifythathere.Thedatabasewill
automaticallyassignitavalue.The“VALUES(?,?,?)”portionindicatesthatwe
areinsertingparameterizedvalues,asopposedtohardcodingvalues.Weusethe
“?”toindicatethatwearenothardcodinganyvalue,butcanchangethevalueat
runtime.
Line7 WeinstantiateaPreparedStatement,whichisneededtoexecutethe
parameterizedSQL.BypassingtheSQLstringasanargument,wehavetoldthe
JDBCdriverwhichSQLcommandwewantittoexecute.Weputthisinstantiation
insideoftry/withblocksothatitwillbeclosedautomatically.
Lines810 Herewedefinewhattheparameters(definedbythe“?”intheSQLstring)arein
turn.Thefirstparameteris“Bob”correspondingtothefirst_namecolumn,the
secondparameteris“Smith”,correspondingtothelast_namecolumn,andthe
thirdparameteris1/13/1976,correspondingtothebirth_datecolumn.
Line11 ThisinstructstheJDBCdrivertoexecutethepreparedstatementwiththegiven
parameters.Withtheparametersset,itwillbeexecutingthiscommand(butstill
usingparametersbehindthescenes):
INSERT INTO Person(first_name, last_name, birth_date)
VALUES (‘Bob’, ‘Smith’, ‘1/13/1976’)
Lines1316Followingsimilarlogictolines811,theselinesinsertanewrowwithfirst_name
=“Jane”,last_name=“Elizabeth”,andbirth_date=“3/15/1979”.
Line35 Thisinvokesourquerymethodwhichwillretrieveanddisplaytherowswehave
inserted.
Line21 Insidethequerymethod,thisSQLstringistoselectallfourcolumnsfromthe
Persontable,inthisorderperson_id,first_name,last_name,birth_date.
Lines2223Astatementiscreatedonline22withtheconn.createStatement()method,and
online23thequery(previouslydefinedonline21)isexecutedwiththe
stmt.executeQuery()method.ThisreturnsanobjectoftypeResultSet,whichhas
allrowsandcolumnsfromtheresults.Thesearecreatedwithinatry/withblock
sothattheyareautomaticallyclosed.
Page40of43
Line24 Thiswhileloopusesthers.next()methodtoiteratethrougheachrow.Aslongas
thereisanotherrowintheresultset,thenext()methodwillreturntrue.
Lines2526Thisprintsouttheresultsofthequeryinatabularformat.Notethatthe
ResultSetclassprovidesmethodssuchasgetString(),getDate(),andgetInt(),to
retrievethespecificfieldsinarow.Thecorrectmethodmustbeusedforthe
correctdatatype.Forexample,getInt()mustbeusedforperson_idsinceitisan
integer,andgetDate()mustbeusedforbirth_datesinceitisadate.Thefirst
argumentofthesemethodsisthecolumnnumber.Forexample,thegetInt()call
specifies“1”asthecolumnnumbersinceperson_idisqueriedfirst.The
getDate()callspecifies“4”asthecolumnnumberisbirth_dateisqueriedlast.
NOTE:ThesourcecodeisavailableinAppendixAsothatyoumaycopyandpasteasneeded.
Run Class
Withtheclassdefined,wecannowrunitwiththeRun/Runmenucommand.
SelecttheUseDatabaseclasstoexecute.
Aftertheclassexecutes,youseetheoutputasbelow.
Noticethattheperson_idautoincrementcolumnstartsat1andincrementsupwardsby1.Further
noticethatBobSmithbornon1/13/1976islistedfirst,followedbyJaneElizabethbornon
3/15/1979.
Page41of43
Next Steps
Congratulations!YouarenowwellonyourwaytoworkingwithSQLite.YouhaveusedaSQLclient,DBBrowserfor
SQLite,tocreateadatabaseaswellasatable.YouhaveusedtheSQLiteJDBCdrivertoadddatatothetableand
retrievedthedatainJava.YourinstructormayaskyoutouseotherSQLcommandsandJDBCfeatures,andyounow
haveaframeworkfromwhichtodoso.Don’tworry.Ifyoucancreateonedatabase,youcancreatemany.Ifyoucan
executeoneSQLcommandinJava,youcanexecutemany.Youarewellonyourway.

Page42of43
Appendix A: Source Code
ThesourcecodefortheUseDatabaseclassisavailablebelowsothatyoucancopyandpasteitasneeded.
packagedatabase;
importjava.sql.*;
publicclassUseDatabase{
privatestaticvoidinsert(Connectionconn)throwsSQLException{
Stringsql="INSERTINTOPerson(first_name,last_name,birth_date)VALUES(?,?,?)";
try(PreparedStatementpstmt=conn.prepareStatement(sql)){
pstmt.setString(1,"Bob");
pstmt.setString(2,"Smith");
pstmt.setDate(3,Date.valueOf("19761
13"));
pstmt.executeUpdate();

pstmt.setString(1,"Jane");
pstmt.setString(2,"Elizabeth");
pstmt.setDate(3,Date.valueOf("1979315"));
pstmt.executeUpdate();
}
}

privatestaticvoidquery(Connectionconn)throwsSQLException{
Stringsql="SELECTperson_id,first_name,last_name,birth_dateFROMPerson";
try(Statementstmt=conn.createStatement();
ResultSet
rs=stmt.executeQuery(sql)){
while(rs.next()){
System.out.printf("%d\t%10s\t%10s\t%tD%n",
rs.getInt(1),rs.getString(2),rs.getString(3),rs.getDate(4));
}
}
}

publicstaticvoidmain(String[]args)throwsSQLException{
Stringurl="jdbc:sqlite:C:/SQLite/GettingStarted.db";
try(Connectionconn=DriverManager.getConnection(url)){
insert
(conn);
query(conn);
}
}
}
Page43of43
Works Cited
SolidIT(March2020).DBEnginesRanking.RetrievedMarch23,2020,fromhttps://dbengines.com/en/ranking
SQLite(March2020).AboutSQLite.RetrievedMarch27,2020,fromhttps://www.sqlite.org/about.html.