Вы находитесь на странице: 1из 38

7/6/2015

SQLitePythontutorial

Home

SQLitePythontutorial
ThisisaPythonprogrammingtutorialfortheSQLitedatabase.ItcoversthebasicsofSQLite
programmingwiththePythonlanguage.YoumightalsowanttocheckthePythontutorial,SQLite
tutorialorMySQLPythontutorialorPostgreSQLPythontutorialonZetCode.

Python GUI App Builder


Build GUI, Web and Mobile Apps. Free Download Windows/OS X/Linux

Prerequisites
Toworkwiththistutorial,wemusthavePythonlanguage,SQLitedatabase,pysqlitelanguage
bindingandthesqlite3commandlinetoolinstalledonthesystem.IfwehavePython2.5+thenwe
onlyneedtoinstallthesqlite3commandlinetool.BoththeSQLitelibraryandthepysqlite
languagebindingarebuiltintothePythonlanguge.
$python
Python2.7.3(default,Jan22013,16:53:07)
[GCC4.7.2]onlinux2
Type"help","copyright","credits"or"license"formoreinformation.
>>>importsqlite3
>>>sqlite3.version
'2.6.0'
http://zetcode.com/db/sqlitepythontutorial/

1/38

7/6/2015

SQLitePythontutorial

>>>sqlite3.sqlite_version
'3.7.13'

Intheshell,welaunchthePythoninteractiveinterpreter.WecanseethePythonversion.Inour
caseitisPython2.7.3.Thesqlite.versionistheversionofthepysqlite(2.6.0),whichisthebinding
ofthePythonlanguagetotheSQLitedatabase.Thesqlite3.sqlite_versiongivesustheversionof
theSQLitedatabaselibrary.Inourcasetheversionis3.7.13.
Nowwearegoingtousethesqlite3commandlinetooltocreateanewdatabase.
$sqlite3test.db
SQLiteversion3.7.132012061102:05:22
Enter".help"forinstructions
EnterSQLstatementsterminatedwitha";"

Weprovideaparametertothesqlite3tooltest.dbisadatabasename.Itisafileonourdisk.Ifit
ispresent,itisopened.Ifnot,itiscreated.
sqlite>.tables
sqlite>.exit
$ls
test.db

The.tablescommandgivesalistoftablesinthetest.dbdatabase.Therearecurrentlynotables.
The.exitcommandterminatestheinteractivesessionofthesqlite3commandlinetool.ThelsUnix
commandshowsthecontentsofthecurrentworkingdirectory.Wecanseethetest.dbfile.Alldata
willbestoredinthissinglefile.

Version
http://zetcode.com/db/sqlitepythontutorial/

2/38

7/6/2015

SQLitePythontutorial

Inthefirstcodeexample,wewillgettheversionoftheSQLitedatabase.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=None
try:
con=lite.connect('test.db')

cur=con.cursor()
cur.execute('SELECTSQLITE_VERSION()')

data=cur.fetchone()

print"SQLiteversion:%s"%data

exceptlite.Error,e:

print"Error%s:"%e.args[0]
sys.exit(1)

finally:

ifcon:
con.close()

IntheabovePythonscriptweconnecttothepreviouslycreatedtest.dbdatabase.Weexecutean
SQLstatementwhichreturnstheversionoftheSQLitedatabase.
importsqlite3aslite
http://zetcode.com/db/sqlitepythontutorial/

3/38

7/6/2015

SQLitePythontutorial

Thesqlite3moduleisusedtoworkwiththeSQLitedatabase.
con=None

WeinitialisetheconvariabletoNone.Incasewecouldnotcreateaconnectiontothedatabase(for
examplethediskisfull),wewouldnothaveaconnectionvariabledefined.Thiswouldleadtoan
errorinthefinallyclause.
con=lite.connect('test.db')

Hereweconnecttothetest.dbdatabase.Theconnect()methodreturnsaconnectionobject.
cur=con.cursor()
cur.execute('SELECTSQLITE_VERSION()')

Fromtheconnection,wegetthecursorobject.Thecursorisusedtotraversetherecordsfromthe
resultset.Wecalltheexecute()methodofthecursorandexecutetheSQLstatement.
data=cur.fetchone()

Wefetchthedata.Sinceweretrieveonlyonerecord,wecallthefetchone()method.
print"SQLiteversion:%s"%data

Weprintthedatathatwehaveretrievedtotheconsole.
exceptlite.Error,e:

print"Error%s:"%e.args[0]
sys.exit(1)
http://zetcode.com/db/sqlitepythontutorial/

4/38

7/6/2015

SQLitePythontutorial

Incaseofanexception,weprintanerrormessageandexitthescriptwithanerrorcode1.
finally:

ifcon:
con.close()

Inthefinalstep,wereleasetheresources.
Inthesecondexample,weagaingettheversionoftheSQLitedatabase.Thistimewewillusethe
withkeyword.

#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=lite.connect('test.db')
withcon:

cur=con.cursor()
cur.execute('SELECTSQLITE_VERSION()')

data=cur.fetchone()

print"SQLiteversion:%s"%data

ThescriptreturnsthecurrentversionoftheSQLitedatabase.Withtheuseofthewithkeyword.The
codeismorecompact.
withcon:
http://zetcode.com/db/sqlitepythontutorial/

5/38

7/6/2015

SQLitePythontutorial

Withthewithkeyword,thePythoninterpreterautomaticallyreleasestheresources.Italsoprovides
errorhandling.

Insertingdata
WewillcreateaCarstableandinsertseveralrowstoit.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=lite.connect('test.db')
withcon:

cur=con.cursor()
cur.execute("CREATETABLECars(IdINT,NameTEXT,PriceINT)")
cur.execute("INSERTINTOCarsVALUES(1,'Audi',52642)")
cur.execute("INSERTINTOCarsVALUES(2,'Mercedes',57127)")
cur.execute("INSERTINTOCarsVALUES(3,'Skoda',9000)")
cur.execute("INSERTINTOCarsVALUES(4,'Volvo',29000)")
cur.execute("INSERTINTOCarsVALUES(5,'Bentley',350000)")
cur.execute("INSERTINTOCarsVALUES(6,'Citroen',21000)")
cur.execute("INSERTINTOCarsVALUES(7,'Hummer',41400)")
cur.execute("INSERTINTOCarsVALUES(8,'Volkswagen',21600)")

TheabovescriptcreatesaCarstableandinserts8rowsintothetable.
cur.execute("CREATETABLECars(IdINT,NameTEXT,PriceINT)")
http://zetcode.com/db/sqlitepythontutorial/

6/38

7/6/2015

SQLitePythontutorial

ThisSQLstatementcreatesanewCarstable.Thetablehasthreecolumns.
cur.execute("INSERTINTOCarsVALUES(1,'Audi',52642)")
cur.execute("INSERTINTOCarsVALUES(2,'Mercedes',57127)")

Thesetwolinesinserttwocarsintothetable.Usingthewithkeyword,thechangesareautomatically
committed.Otherwise,wewouldhavetocommitthemmanually.
sqlite>.modecolumn
sqlite>.headerson

Weverifythewrittendatawiththesqlite3tool.Firstwemodifythewaythedataisdisplayedinthe
console.Weusethecolumnmodeandturnontheheaders.
sqlite>SELECT*FROMCars;
IdNamePrice

1Audi52642
2Mercedes57127
3Skoda9000
4Volvo29000
5Bentley350000
6Citroen21000
7Hummer41400
8Volkswagen21600

ThisisthedatathatwehavewrittentotheCarstable.
Wearegoingtocreatethesametable.Thistimeusingtheconvenienceexecutemany()method.
http://zetcode.com/db/sqlitepythontutorial/

7/38

7/6/2015

SQLitePythontutorial

#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
cars=(
(1,'Audi',52642),
(2,'Mercedes',57127),
(3,'Skoda',9000),
(4,'Volvo',29000),
(5,'Bentley',350000),
(6,'Hummer',41400),
(7,'Volkswagen',21600)
)

con=lite.connect('test.db')
withcon:

cur=con.cursor()

cur.execute("DROPTABLEIFEXISTSCars")
cur.execute("CREATETABLECars(IdINT,NameTEXT,PriceINT)")
cur.executemany("INSERTINTOCarsVALUES(?,?,?)",cars)

ThisscriptdropsaCarstableifitexistsand(re)createsit.
cur.execute("DROPTABLEIFEXISTSCars")
cur.execute("CREATETABLECars(IdINT,NameTEXT,PriceINT)")

ThefirstSQLstatementdropstheCarstableifitexists.ThesecondSQLstatementcreatestheCars
table.
http://zetcode.com/db/sqlitepythontutorial/

8/38

7/6/2015

SQLitePythontutorial

cur.executemany("INSERTINTOCarsVALUES(?,?,?)",cars)

Weinsert8rowsintothetableusingtheconvenienceexecutemany()method.Thefirstparameterof
thismethodisaparameterizedSQLstatement.Thesecondparameteristhedata,intheformof
tupleoftuples.
WeprovideanotherwaytocreateourCarstable.Wecommitthechangesmanuallyandprovideour
ownerrorhandling.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
try:
con=lite.connect('test.db')
cur=con.cursor()
cur.executescript("""
DROPTABLEIFEXISTSCars;
CREATETABLECars(IdINT,NameTEXT,PriceINT);
INSERTINTOCarsVALUES(1,'Audi',52642);
INSERTINTOCarsVALUES(2,'Mercedes',57127);
INSERTINTOCarsVALUES(3,'Skoda',9000);
INSERTINTOCarsVALUES(4,'Volvo',29000);
INSERTINTOCarsVALUES(5,'Bentley',350000);
INSERTINTOCarsVALUES(6,'Citroen',21000);
INSERTINTOCarsVALUES(7,'Hummer',41400);
INSERTINTOCarsVALUES(8,'Volkswagen',21600);
""")
con.commit()
http://zetcode.com/db/sqlitepythontutorial/

9/38

7/6/2015

SQLitePythontutorial

exceptlite.Error,e:

ifcon:
con.rollback()

print"Error%s:"%e.args[0]
sys.exit(1)

finally:

ifcon:
con.close()

Intheabovescriptwe(re)createtheCarstableusingtheexecutescript()method.
cur.executescript("""
DROPTABLEIFEXISTSCars;
CREATETABLECars(IdINT,NameTEXT,PriceINT);
INSERTINTOCarsVALUES(1,'Audi',52642);
INSERTINTOCarsVALUES(2,'Mercedes',57127);
...

Theexecutescript()methodallowsustoexecutethewholeSQLcodeinonestep.
con.commit()

Withoutthewithkeyword,thechangesmustbecommittedusingthecommit()method.
exceptlite.Error,e:

ifcon:
con.rollback()

http://zetcode.com/db/sqlitepythontutorial/

10/38

7/6/2015

SQLitePythontutorial

print"Error%s:"%e.args[0]
sys.exit(1)

Incaseofanerror,thechangesarerolledbackandanerrormessageisprintedtotheterminal.

Thelastinsertedrowid
Sometimes,weneedtodeterminetheidofthelastinsertedrow.InPythonSQLite,weusethe
lastrowidattributeofthecursorobject.

#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=lite.connect(':memory:')
withcon:

cur=con.cursor()
cur.execute("CREATETABLEFriends(IdINTEGERPRIMARYKEY,NameTEXT);")
cur.execute("INSERTINTOFriends(Name)VALUES('Tom');")
cur.execute("INSERTINTOFriends(Name)VALUES('Rebecca');")
cur.execute("INSERTINTOFriends(Name)VALUES('Jim');")
cur.execute("INSERTINTOFriends(Name)VALUES('Robert');")

lid=cur.lastrowid
print"ThelastIdoftheinsertedrowis%d"%lid

WecreateaFriendstableinmemory.TheIdisautomaticallyincremented.
cur.execute("CREATETABLEFriends(IdINTEGERPRIMARYKEY,NameTEXT);")
http://zetcode.com/db/sqlitepythontutorial/

11/38

7/6/2015

SQLitePythontutorial

InSQLite,INTEGERPRIMARYKEYcolumnisautoincremented.ThereisalsoanAUTOINCREMENTkeyword.
WhenusedinINTEGERPRIMARYKEYAUTOINCREMENTaslightlydifferentalgorithmforIdcreationisused.
cur.execute("INSERTINTOFriends(Name)VALUES('Tom');")
cur.execute("INSERTINTOFriends(Name)VALUES('Rebecca');")
cur.execute("INSERTINTOFriends(Name)VALUES('Jim');")
cur.execute("INSERTINTOFriends(Name)VALUES('Robert');")

Whenusingautoincrement,wehavetoexplicitlystatethecolumnnames,omittingtheonethatis
autoincremented.ThefourstatementsinsertfourrowsintotheFriendstable.
lid=cur.lastrowid

Usingthelastrowidwegetthelastinsertedrowid.
$./lastrow.py
ThelastIdoftheinsertedrowis4

Weseetheoutputofthescript.

Retrievingdata
Nowthatwehaveinsertedsomedataintothedatabase,wewanttofetchitback.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
http://zetcode.com/db/sqlitepythontutorial/

12/38

7/6/2015

SQLitePythontutorial

con=lite.connect('test.db')
withcon:

cur=con.cursor()
cur.execute("SELECT*FROMCars")
rows=cur.fetchall()
forrowinrows:
printrow

Inthisexample,weretrievealldatafromtheCarstable.
cur.execute("SELECT*FROMCars")

ThisSQLstatementselectsalldatafromtheCarstable.
rows=cur.fetchall()

Thefetchall()methodgetsallrecords.Itreturnsaresultset.Technically,itisatupleoftuples.
Eachoftheinnertuplesrepresentarowinthetable.
forrowinrows:
printrow

Weprintthedatatotheconsole,rowbyrow.
$./retrieveall.py
(1,u'Audi',52642)
(2,u'Mercedes',57127)
http://zetcode.com/db/sqlitepythontutorial/

13/38

7/6/2015

SQLitePythontutorial

(3,u'Skoda',9000)
(4,u'Volvo',29000)
(5,u'Bentley',350000)
(6,u'Citroen',21000)
(7,u'Hummer',41400)
(8,u'Volkswagen',21600)

Thisistheoutputoftheexample.
Returningalldataatatimemaynotbefeasible.Wecanfetchrowsonebyone.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=lite.connect('test.db')
withcon:

cur=con.cursor()
cur.execute("SELECT*FROMCars")
whileTrue:

row=cur.fetchone()

ifrow==None:
break

printrow[0],row[1],row[2]

http://zetcode.com/db/sqlitepythontutorial/

14/38

7/6/2015

SQLitePythontutorial

InthisscriptweconnecttothedatabaseandfetchtherowsoftheCarstableonebyone.
whileTrue:

Weaccessthedatafromthewhileloop.Whenwereadthelastrow,theloopisterminated.
row=cur.fetchone()
ifrow==None:
break

Thefetchone()methodreturnsthenextrowfromthetable.Ifthereisnomoredataleft,itreturns
None.Inthiscasewebreaktheloop.

printrow[0],row[1],row[2]

Thedataisreturnedintheformofatuple.Hereweselectrecordsfromthetuple.ThefirstistheId,
thesecondisthecarnameandthethirdisthepriceofthecar.
$./retrieveonebyone.py
1Audi52642
2Mercedes57127
3Skoda9000
4Volvo29000
5Bentley350000
6Citroen21000
7Hummer41400
8Volkswagen21600

http://zetcode.com/db/sqlitepythontutorial/

15/38

7/6/2015

SQLitePythontutorial

Thisistheoutputoftheexample.

Thedictionarycursor
Thedefaultcursorreturnsthedatainatupleoftuples.Whenweuseadictionarycursor,thedatais
sentintheformofPythondictionaries.Thiswaywecanrefertothedatabytheircolumnnames.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite

con=lite.connect('test.db')
withcon:

con.row_factory=lite.Row

cur=con.cursor()
cur.execute("SELECT*FROMCars")
rows=cur.fetchall()
forrowinrows:
print"%s%s%s"%(row["Id"],row["Name"],row["Price"])

Inthisexample,weprintthecontentsoftheCarstableusingthedictionarycursor.
con.row_factory=lite.Row

Weselectadictionarycursor.Nowwecanaccessrecordsbythenamesofcolumns.
http://zetcode.com/db/sqlitepythontutorial/

16/38

7/6/2015

SQLitePythontutorial

forrowinrows:
print"%s%s%s"%(row["Id"],row["Name"],row["Price"])

Thedataisaccessedbythecolumnnames.

Parameterizedqueries
Nowwewillconcernourselveswithparameterizedqueries.Whenweuseparameterizedqueries,we
useplaceholdersinsteadofdirectlywritingthevaluesintothestatements.Parameterizedqueries
increasesecurityandperformance.
ThePythonsqlite3modulesupportstwotypesofplaceholders:questionmarksandnamed
placeholders.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
uId=1
uPrice=62300
con=lite.connect('test.db')
withcon:
cur=con.cursor()
cur.execute("UPDATECarsSETPrice=?WHEREId=?",(uPrice,uId))
con.commit()

http://zetcode.com/db/sqlitepythontutorial/

17/38

7/6/2015

SQLitePythontutorial

print"Numberofrowsupdated:%d"%cur.rowcount

Weupdateapriceofonecar.Inthiscodeexample,weusethequestionmarkplaceholders.
cur.execute("UPDATECarsSETPrice=?WHEREId=?",(uPrice,uId))

Thequestionmarks?areplaceholdersforvalues.Thevaluesareaddedtotheplaceholders.
print"Numberofrowsupdated:%d"%cur.rowcount

Therowcountpropertyreturnsthenumberofupdatedrows.Inourcaseonerowwasupdated.
$./prepared.py
Numberofrowsupdated:1

IdNamePrice

1Audi62300

Thepriceofthecarwasupdated.
Thesecondexampleusesparameterizedstatementswithnamedplaceholders.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
uId=4

http://zetcode.com/db/sqlitepythontutorial/

18/38

7/6/2015

SQLitePythontutorial

con=lite.connect('test.db')
withcon:
cur=con.cursor()
cur.execute("SELECTName,PriceFROMCarsWHEREId=:Id",
{"Id":uId})
con.commit()

row=cur.fetchone()
printrow[0],row[1]

Weselectanameandapriceofacarusingnamedplaceholders.
cur.execute("SELECTName,PriceFROMCarsWHEREId=:Id",
{"Id":uId})

Thenamedplaceholdersstartwithacoloncharacter.

Insertingimages
Inthissection,wearegoingtoinsertanimagetotheSQLitedatabase.Notethatsomepeopleargue
againstputtingimagesintodatabases.Hereweonlyshowhowtodoit.Wedonotdwellinto
technicalissuesofwhethertosaveimagesindatabasesornot.
sqlite>CREATETABLEImages(IdINTEGERPRIMARYKEY,DataBLOB);

Forthisexample,wecreateanewtablecalledImages.Fortheimages,weusetheBLOBdatatype,
whichstandsforBinaryLargeObjects.

http://zetcode.com/db/sqlitepythontutorial/

19/38

7/6/2015

SQLitePythontutorial

#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys

defreadImage():
try:
fin=open("woman.jpg","rb")
img=fin.read()
returnimg

exceptIOError,e:
print"Error%d:%s"%(e.args[0],e.args[1])
sys.exit(1)
finally:

iffin:
fin.close()

try:
con=lite.connect('test.db')

cur=con.cursor()
data=readImage()
binary=lite.Binary(data)
cur.execute("INSERTINTOImages(Data)VALUES(?)",(binary,))
con.commit()

exceptlite.Error,e:
http://zetcode.com/db/sqlitepythontutorial/

20/38

7/6/2015

SQLitePythontutorial

ifcon:
con.rollback()

print"Error%s:"%e.args[0]
sys.exit(1)

finally:

ifcon:
con.close()

Inthisscript,wereadanimagefromthecurrentworkingdirectoryandwriteitintotheImagestable
oftheSQLitetest.dbdatabase.
try:
fin=open("woman.jpg","rb")
img=fin.read()
returnimg

Wereadbinarydatafromthefilesystem.WehaveaJPGimagecalledwoman.jpg.
binary=lite.Binary(data)

ThedataisencodedusingtheSQLiteBinaryobject.
cur.execute("INSERTINTOImages(Data)VALUES(?)",(binary,))

ThisSQLstatementisusedtoinserttheimageintothedatabase.

Readingimages
http://zetcode.com/db/sqlitepythontutorial/

21/38

7/6/2015

SQLitePythontutorial

Inthissection,wearegoingtoperformthereverseoperation.Wewillreadanimagefromthe
databasetable.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys

defwriteImage(data):

try:
fout=open('woman2.jpg','wb')
fout.write(data)

exceptIOError,e:
print"Error%d:%s"%(e.args[0],e.args[1])
sys.exit(1)

finally:

iffout:
fout.close()

try:
con=lite.connect('test.db')

cur=con.cursor()
cur.execute("SELECTDataFROMImagesLIMIT1")
data=cur.fetchone()[0]

writeImage(data)

http://zetcode.com/db/sqlitepythontutorial/

22/38

7/6/2015

SQLitePythontutorial

exceptlite.Error,e:

print"Error%s:"%e.args[0]
sys.exit(1)

finally:

ifcon:
con.close()

WereadimagedatafromtheImagestableandwriteittoanotherfile,whichwecallwoman2.jpg.
try:
fout=open('woman2.jpg','wb')
fout.write(data)

Weopenabinaryfileinawritingmode.Thedatafromthedatabaseiswrittentothefile.
cur.execute("SELECTDataFROMImagesLIMIT1")
data=cur.fetchone()[0]

ThesetwolinesselectandfetchdatafromtheImagestable.Weobtainthebinarydatafromthefirst
row.

Metadata
Metadataisinformationaboutthedatainthedatabase.MetadatainaSQLitecontainsinformation
aboutthetablesandcolumns,inwhichwestoredata.NumberofrowsaffectedbyanSQL
statementisametadata.Numberofrowsandcolumnsreturnedinaresultsetbelongtometadata
aswell.
http://zetcode.com/db/sqlitepythontutorial/

23/38

7/6/2015

SQLitePythontutorial

MetadatainSQLitecanbeobtainedusingthePRAGMAcommand.SQLiteobjectsmayhaveattributes,
whicharemetadata.Finally,wecanalsoobtainspecificmetatadafromqueryingtheSQLitesystem
sqlite_mastertable.

#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=lite.connect('test.db')
withcon:

cur=con.cursor()

cur.execute('PRAGMAtable_info(Cars)')

data=cur.fetchall()

fordindata:
printd[0],d[1],d[2]

Inthisexample,weissuethePRAGMAtable_info(tableName)command,togetsomemetadatainfo
aboutourCarstable.
cur.execute('PRAGMAtable_info(Cars)')

ThePRAGMAtable_info(tableName)commandreturnsonerowforeachcolumnintheCarstable.
Columnsintheresultsetincludethecolumnordernumber,columnname,datatype,whetheror
notthecolumncanbeNULL,andthedefaultvalueforthecolumn.
http://zetcode.com/db/sqlitepythontutorial/

24/38

7/6/2015

SQLitePythontutorial

fordindata:
printd[0],d[1],d[2]

Fromtheprovidedinformation,weprintthecolumnordernumber,columnnameandcolumndata
type.
$./colnames1.py
0IdINT
1NameTEXT
2PriceINT

Outputoftheexample.
NextwewillprintallrowsfromtheCarstablewiththeircolumnnames.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=lite.connect('test.db')
withcon:

cur=con.cursor()
cur.execute('SELECT*FROMCars')

col_names=[cn[0]forcnincur.description]

rows=cur.fetchall()

print"%s%10s%s"%(col_names[0],col_names[1],col_names[2])
http://zetcode.com/db/sqlitepythontutorial/

25/38

7/6/2015

SQLitePythontutorial

forrowinrows:
print"%2s%10s%s"%row

WeprintthecontentsoftheCarstabletotheconsole.Now,weincludethenamesofthecolumns
too.Therecordsarealignedwiththecolumnnames.
col_names=[cn[0]forcnincur.description]

Wegetthecolumnnamesfromthedescriptionpropertyofthecursorobject.
print"%s%10s%s"%(col_names[0],col_names[1],col_names[2])

ThislineprintsthreecolumnnamesoftheCarstable.
forrowinrows:
print"%2s%10s%s"%row

Weprinttherowsusingtheforloop.Thedataisalignedwiththecolumnnames.
$./colnames2.py
IdNamePrice
1Audi52642
2Mercedes57127
3Skoda9000
4Volvo29000
5Bentley350000
6Citroen21000
7Hummer41400
http://zetcode.com/db/sqlitepythontutorial/

26/38

7/6/2015

SQLitePythontutorial

8Volkswagen21600

Output.
Inourlastexamplerelatedtothemetadata,wewilllistalltablesinthetest.dbdatabase.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
con=lite.connect('test.db')
withcon:

cur=con.cursor()
cur.execute("SELECTnameFROMsqlite_masterWHEREtype='table'")
rows=cur.fetchall()
forrowinrows:
printrow[0]

Thecodeexampleprintsallavailabletablesinthecurrentdatabasetotheterminal.
cur.execute("SELECTnameFROMsqlite_masterWHEREtype='table'")

Thetablenamesarestoredinsidethesystemsqlite_mastertable.
$./listtables.py
Images
sqlite_sequence
http://zetcode.com/db/sqlitepythontutorial/

27/38

7/6/2015

SQLitePythontutorial

Salaries
Cars

Thesewerethetablesonmysystem.

Exportandimportofdata
WecandumpdatainanSQLformattocreateasimplebackupofourdatabasetables.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys
cars=(
(1,'Audi',52643),
(2,'Mercedes',57642),
(3,'Skoda',9000),
(4,'Volvo',29000),
(5,'Bentley',350000),
(6,'Hummer',41400),
(7,'Volkswagen',21600)
)
defwriteData(data):

f=open('cars.sql','w')

withf:
f.write(data)

con=lite.connect(':memory:')
http://zetcode.com/db/sqlitepythontutorial/

28/38

7/6/2015

SQLitePythontutorial

withcon:

cur=con.cursor()

cur.execute("DROPTABLEIFEXISTSCars")
cur.execute("CREATETABLECars(IdINT,NameTEXT,PriceINT)")
cur.executemany("INSERTINTOCarsVALUES(?,?,?)",cars)
cur.execute("DELETEFROMCarsWHEREPrice<30000")

data='\n'.join(con.iterdump())

writeData(data)

Intheaboveexample,werecreatetheCarstableinthememory.Wedeletesomerowsfromthetable
anddumpthecurrentstateofthetableintoacars.sqlfile.Thisfilecanserveasacurrentbackupof
thetable.
defwriteData(data):

f=open('cars.sql','w')

withf:
f.write(data)

Thedatafromthetableisbeingwrittentothefile.
con=lite.connect(':memory:')

Wecreateatemporarytableinthememory.
cur.execute("DROPTABLEIFEXISTSCars")
cur.execute("CREATETABLECars(IdINT,NameTEXT,PriceINT)")
http://zetcode.com/db/sqlitepythontutorial/

29/38

7/6/2015

SQLitePythontutorial

cur.executemany("INSERTINTOCarsVALUES(?,?,?)",cars)
cur.execute("DELETEFROMCarsWHEREPrice<30000")

TheselinescreateaCarstable,insertvaluesanddeleterows,wherethePriceislessthan30000
units.
data='\n'.join(con.iterdump())

Thecon.iterdump()returnsaniteratortodumpthedatabaseinanSQLtextformat.Thebuiltin
join()functiontakestheiteratorandjoinsallthestringsintheiteratorseparatedbyanewline.

Thisdataiswrittentothecars.sqlfileinthewriteData()function.
$catcars.sql
BEGINTRANSACTION;
CREATETABLECars(IdINT,NameTEXT,PriceINT);
INSERTINTO"Cars"VALUES(1,'Audi',52643);
INSERTINTO"Cars"VALUES(2,'Mercedes',57642);
INSERTINTO"Cars"VALUES(5,'Bentley',350000);
INSERTINTO"Cars"VALUES(6,'Hummer',41400);
COMMIT;

ThecontentsofthedumpedinmemoryCarstable.
Nowwearegoingtoperformareverseoperation.Wewillimportthedumpedtablebackinto
memory.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
http://zetcode.com/db/sqlitepythontutorial/

30/38

7/6/2015

SQLitePythontutorial

importsys

defreadData():

f=open('cars.sql','r')

withf:
data=f.read()
returndata

con=lite.connect(':memory:')
withcon:
cur=con.cursor()

sql=readData()
cur.executescript(sql)

cur.execute("SELECT*FROMCars")

rows=cur.fetchall()

forrowinrows:
printrow

Inthisscript,wereadthecontentsofthecars.sqlfileandexecuteit.Thiswillrecreatethedumped
table.
defreadData():

f=open('cars.sql','r')

http://zetcode.com/db/sqlitepythontutorial/

31/38

7/6/2015

SQLitePythontutorial

withf:
data=f.read()
returndata

InsidethereadData()methodwereadthecontentsofthecars.sqltable.
cur.executescript(sql)

Wecalltheexecutescript()methodtolaunchtheSQLscript.
cur.execute("SELECT*FROMCars")
rows=cur.fetchall()
forrowinrows:
printrow

Weverifythedata.
$./import.py
(1,u'Audi',52643)
(2,u'Mercedes',57642)
(5,u'Bentley',350000)
(6,u'Hummer',41400)

TheoutputshowsthatwehavesuccessfullyrecreatedthesavedCarstable.

Transactions
Atransactionisanatomicunitofdatabaseoperationsagainstthedatainoneormoredatabases.
http://zetcode.com/db/sqlitepythontutorial/

32/38

7/6/2015

SQLitePythontutorial

TheeffectsofalltheSQLstatementsinatransactioncanbeeitherallcommittedtothedatabaseor
allrolledback.
InSQLite,anycommandotherthantheSELECTwillstartanimplicittransaction.Also,withina
transactionacommandlikeCREATETABLE...,VACUUM,PRAGMA,willcommitpreviouschangesbefore
executing.
ManualtransactionsarestartedwiththeBEGINTRANSACTIONstatementandfinishedwiththeCOMMIT
orROLLBACKstatements.
SQLitesupportsthreenonstandardtransactionlevels:DEFERRED,IMMEDIATEandEXCLUSIVE.SQLite
Pythonmodulealsosupportsanautocommitmode,whereallchangestothetablesareimmediately
effective.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys

try:
con=lite.connect('test.db')
cur=con.cursor()
cur.execute("DROPTABLEIFEXISTSFriends")
cur.execute("CREATETABLEFriends(IdINTEGERPRIMARYKEY,NameTEXT)")
cur.execute("INSERTINTOFriends(Name)VALUES('Tom')")
cur.execute("INSERTINTOFriends(Name)VALUES('Rebecca')")
cur.execute("INSERTINTOFriends(Name)VALUES('Jim')")
cur.execute("INSERTINTOFriends(Name)VALUES('Robert')")

#con.commit()

http://zetcode.com/db/sqlitepythontutorial/

33/38

7/6/2015

SQLitePythontutorial

exceptlite.Error,e:

ifcon:
con.rollback()

print"Error%s:"%e.args[0]
sys.exit(1)

finally:

ifcon:
con.close()

WecreateaFriendstableandtrytofillitwithdata.However,aswewillsee,thedataisnot
committed.
#con.commit()

Thecommit()methodiscommented.Ifweuncommenttheline,thedatawillbewrittentothetable.
sqlite>.tables
CarsFriendsImagesSalariesTemporary

sqlite>SELECTCount(Id)FROMFriends;
Count(Id)

Thetableiscreatedbutthedataisnotwrittentothetable.
Inthesecondexamplewedemonstratethatsomecommandsimplicitlycommitpreviouschangesto
http://zetcode.com/db/sqlitepythontutorial/

34/38

7/6/2015

SQLitePythontutorial

thedatabase.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys

try:
con=lite.connect('test.db')
cur=con.cursor()
cur.execute("DROPTABLEIFEXISTSFriends")
cur.execute("CREATETABLEFriends(IdINTEGERPRIMARYKEY,NameTEXT)")
cur.execute("INSERTINTOFriends(Name)VALUES('Tom')")
cur.execute("INSERTINTOFriends(Name)VALUES('Rebecca')")
cur.execute("INSERTINTOFriends(Name)VALUES('Jim')")
cur.execute("INSERTINTOFriends(Name)VALUES('Robert')")
cur.execute("CREATETABLEIFNOTEXISTSTemporary(IdINT)")

exceptlite.Error,e:

ifcon:
con.rollback()

print"Error%s:"%e.args[0]
sys.exit(1)

finally:

ifcon:
con.close()

Again,wedonotcallthecommit()commandexplicitly.Butthistime,thedataiswrittentothe
http://zetcode.com/db/sqlitepythontutorial/

35/38

7/6/2015

SQLitePythontutorial

Friendstable.
cur.execute("CREATETABLEIFNOTEXISTSTemporary(IdINT)")

ThisSQLstatementwillcreateanewtable.Italsocommitsthepreviouschanges.
$./implcommit.py

sqlite>SELECT*FROMFriends;
IdName

1Tom
2Rebecca
3Jim
4Robert

ThedatahasbeenwrittentotheFriendstable.
Intheautocommitmode,anSQLstatementisexecutedimmediately.
#!/usr/bin/python
#*coding:utf8*
importsqlite3aslite
importsys

try:
con=lite.connect('test.db',isolation_level=None)
cur=con.cursor()
http://zetcode.com/db/sqlitepythontutorial/

36/38

7/6/2015

SQLitePythontutorial

cur.execute("DROPTABLEIFEXISTSFriends")
cur.execute("CREATETABLEFriends(IdINTEGERPRIMARYKEY,NameTEXT)")
cur.execute("INSERTINTOFriends(Name)VALUES('Tom')")
cur.execute("INSERTINTOFriends(Name)VALUES('Rebecca')")
cur.execute("INSERTINTOFriends(Name)VALUES('Jim')")
cur.execute("INSERTINTOFriends(Name)VALUES('Robert')")

exceptlite.Error,e:

print"Error%s:"%e.args[0]
sys.exit(1)

finally:

ifcon:
con.close()

Inthisexample,weconnecttothedatabaseintheautocommitmode.
con=lite.connect('test.db',isolation_level=None)

Wehaveanautocommitmode,whenwesettheisolation_leveltoNone.
$./autocommit.py

sqlite>SELECT*FROMFriends;
IdName

1Tom
2Rebecca
3Jim
http://zetcode.com/db/sqlitepythontutorial/

37/38

7/6/2015

SQLitePythontutorial

4Robert

ThedatawassuccessfullycommittedtotheFriendstable.
Like

Share

61

112

Tweet

58

ThiswasSQLitePythontutorial.ZetCodehasacompleteebookforSQLitePython:
SQLitePythonebook.
Home TopofPage
ZetCodelastmodifiedNovember20,2014

http://zetcode.com/db/sqlitepythontutorial/

20072015JanBodnar

38/38