sqlite3 — DB-API 2.0 interface for SQLite databases¶
Source code:Lib/sqlite3/
SQLite is a C library that provides a lightweight disk-based database thatdoesn’t require a separate server process and allows accessing the databaseusing a nonstandard variant of the SQL query language. Some applications can useSQLite for internal data storage. It’s also possible to prototype anapplication using SQLite and then port the code to a larger database such asPostgreSQL or Oracle.
The sqlite3 module was written by Gerhard Häring. It provides an SQL interfacecompliant with the DB-API 2.0 specification described byPEP 249.
To use the module, start by creating aConnection object thatrepresents the database. Here the data will be stored in theexample.db file:
importsqlite3con=sqlite3.connect('example.db')
The special path name:memory: can be provided to create a temporarydatabase in RAM.
Once aConnection has been established, create aCursor objectand call itsexecute() method to perform SQL commands:
cur=con.cursor()# Create tablecur.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''')# Insert a row of datacur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")# Save (commit) the changescon.commit()# We can also close the connection if we are done with it.# Just be sure any changes have been committed or they will be lost.con.close()
The saved data is persistent: it can be reloaded in a subsequent session evenafter restarting the Python interpreter:
importsqlite3con=sqlite3.connect('example.db')cur=con.cursor()
To retrieve data after executing a SELECT statement, either treat the cursor asaniterator, call the cursor’sfetchone() method toretrieve a single matching row, or callfetchall() to get a listof the matching rows.
This example uses the iterator form:
>>>forrowincur.execute('SELECT * FROM stocks ORDER BY price'): print(row)('2006-01-05', 'BUY', 'RHAT', 100, 35.14)('2006-03-28', 'BUY', 'IBM', 1000, 45.0)('2006-04-06', 'SELL', 'IBM', 500, 53.0)('2006-04-05', 'BUY', 'MSFT', 1000, 72.0)
SQL operations usually need to use values from Python variables. However,beware of using Python’s string operations to assemble queries, as theyare vulnerable to SQL injection attacks (see thexkcd webcomic for a humorous example of what can go wrong):
# Never do this -- insecure!symbol='RHAT'cur.execute("SELECT * FROM stocks WHERE symbol = '%s'"%symbol)
Instead, use the DB-API’s parameter substitution. To insert a variable into aquery string, use a placeholder in the string, and substitute the actual valuesinto the query by providing them as atuple of values to the secondargument of the cursor’sexecute() method. An SQL statement mayuse one of two kinds of placeholders: question marks (qmark style) or namedplaceholders (named style). For the qmark style,parameters must be asequence. For the named style, it can be either asequence ordict instance. The length of thesequence must match the number of placeholders, or aProgrammingError is raised. If adict is given, it must containkeys for all named parameters. Any extra items are ignored. Here’s an example ofboth styles:
importsqlite3con=sqlite3.connect(":memory:")cur=con.cursor()cur.execute("create table lang (name, first_appeared)")# This is the qmark style:cur.execute("insert into lang values (?, ?)",("C",1972))# The qmark style used with executemany():lang_list=[("Fortran",1957),("Python",1991),("Go",2009),]cur.executemany("insert into lang values (?, ?)",lang_list)# And this is the named style:cur.execute("select * from lang where first_appeared=:year",{"year":1972})print(cur.fetchall())con.close()
See also
- https://www.sqlite.org
The SQLite web page; the documentation describes the syntax and theavailable data types for the supported SQL dialect.
- https://www.w3schools.com/sql/
Tutorial, reference and examples for learning SQL syntax.
- PEP 249 - Database API Specification 2.0
PEP written by Marc-André Lemburg.
Module functions and constants¶
sqlite3.apilevel¶String constant stating the supported DB-API level. Required by the DB-API.Hard-coded to
"2.0".
sqlite3.paramstyle¶String constant stating the type of parameter marker formatting expected bythe
sqlite3module. Required by the DB-API. Hard-coded to"qmark".Note
The
sqlite3module supports bothqmarkandnumericDB-APIparameter styles, because that is what the underlying SQLite librarysupports. However, the DB-API does not allow multiple values fortheparamstyleattribute.
sqlite3.version¶The version number of this module, as a string. This is not the version ofthe SQLite library.
sqlite3.version_info¶The version number of this module, as a tuple of integers. This is not theversion of the SQLite library.
sqlite3.sqlite_version¶The version number of the run-time SQLite library, as a string.
sqlite3.sqlite_version_info¶The version number of the run-time SQLite library, as a tuple of integers.
sqlite3.threadsafety¶Integer constant required by the DB-API, stating the level of thread safetythe
sqlite3module supports. Currently hard-coded to1, meaning“Threads may share the module, but not connections.” However, this may notalways be true. You can check the underlying SQLite library’s compile-timethreaded mode using the following query:importsqlite3con=sqlite3.connect(":memory:")con.execute(""" select * from pragma_compile_options where compile_options like 'THREADSAFE=%'""").fetchall()
Note that theSQLITE_THREADSAFE levels do not match the DB-API 2.0
threadsafetylevels.
sqlite3.PARSE_DECLTYPES¶This constant is meant to be used with thedetect_types parameter of the
connect()function.Setting it makes the
sqlite3module parse the declared type for eachcolumn it returns. It will parse out the first word of the declared type,i. e. for “integer primary key”, it will parse out “integer”, or for“number(10)” it will parse out “number”. Then for that column, it will lookinto the converters dictionary and use the converter function registered forthat type there.
sqlite3.PARSE_COLNAMES¶This constant is meant to be used with thedetect_types parameter of the
connect()function.Setting this makes the SQLite interface parse the column name for each column itreturns. It will look for a string formed [mytype] in there, and then decidethat ‘mytype’ is the type of the column. It will try to find an entry of‘mytype’ in the converters dictionary and then use the converter function foundthere to return the value. The column name found in
Cursor.descriptiondoes not include the type, i. e. if you use something like'as"Expirationdate[datetime]"'in your SQL, then we will parse outeverything until the first'['for the column name and stripthe preceding space: the column name would simply be “Expiration date”.
sqlite3.connect(database[,timeout,detect_types,isolation_level,check_same_thread,factory,cached_statements,uri])¶Opens a connection to the SQLite database filedatabase. By default returns a
Connectionobject, unless a customfactory is given.database is apath-like object giving the pathname (absolute orrelative to the current working directory) of the database file to be opened.You can use
":memory:"to open a database connection to a database thatresides in RAM instead of on disk.When a database is accessed by multiple connections, and one of the processesmodifies the database, the SQLite database is locked until that transaction iscommitted. Thetimeout parameter specifies how long the connection should waitfor the lock to go away until raising an exception. The default for the timeoutparameter is 5.0 (five seconds).
For theisolation_level parameter, please see the
isolation_levelproperty ofConnectionobjects.SQLite natively supports only the types TEXT, INTEGER, REAL, BLOB and NULL. Ifyou want to use other types you must add support for them yourself. Thedetect_types parameter and the using customconverters registered with themodule-level
register_converter()function allow you to easily do that.detect_types defaults to 0 (i. e. off, no type detection), you can set it toany combination of
PARSE_DECLTYPESandPARSE_COLNAMESto turntype detection on. Due to SQLite behaviour, types can’t be detected for generatedfields (for examplemax(data)), even whendetect_types parameter is set. Insuch case, the returned type isstr.By default,check_same_thread is
Trueand only the creating thread mayuse the connection. If setFalse, the returned connection may be sharedacross multiple threads. When using multiple threads with the same connectionwriting operations should be serialized by the user to avoid data corruption.By default, the
sqlite3module uses itsConnectionclass for theconnect call. You can, however, subclass theConnectionclass and makeconnect()use your class instead by providing your class for thefactoryparameter.Consult the sectionSQLite and Python types of this manual for details.
The
sqlite3module internally uses a statement cache to avoid SQL parsingoverhead. If you want to explicitly set the number of statements that are cachedfor the connection, you can set thecached_statements parameter. The currentlyimplemented default is to cache 100 statements.Ifuri is
True,database is interpreted as aURI with a file path and an optionalquery string. The scheme partmust be"file:". The path can be arelative or absolute file path. The query string allows us to passparameters to SQLite. Some useful URI tricks include:# Open a database in read-only mode.con=sqlite3.connect("file:template.db?mode=ro",uri=True)# Don't implicitly create a new database file if it does not already exist.# Will raise sqlite3.OperationalError if unable to open a database file.con=sqlite3.connect("file:nosuchdb.db?mode=rw",uri=True)# Create a shared named in-memory database.con1=sqlite3.connect("file:mem1?mode=memory&cache=shared",uri=True)con2=sqlite3.connect("file:mem1?mode=memory&cache=shared",uri=True)con1.executescript("create table t(t); insert into t values(28);")rows=con2.execute("select * from t").fetchall()
More information about this feature, including a list of recognizedparameters, can be found in theSQLite URI documentation.
Raises anauditing event
sqlite3.connectwith argumentdatabase.Changed in version 3.4:Added theuri parameter.
Changed in version 3.7:database can now also be apath-like object, not only a string.
sqlite3.register_converter(typename,callable)¶Registers a callable to convert a bytestring from the database into a customPython type. The callable will be invoked for all database values that are ofthe typetypename. Confer the parameterdetect_types of the
connect()function for how the type detection works. Note thattypename and the name ofthe type in your query are matched in case-insensitive manner.
sqlite3.register_adapter(type,callable)¶Registers a callable to convert the custom Python typetype into one ofSQLite’s supported types. The callablecallable accepts as single parameterthe Python value, and must return a value of the following types: int,float, str or bytes.
sqlite3.complete_statement(sql)¶Returns
Trueif the stringsql contains one or more complete SQLstatements terminated by semicolons. It does not verify that the SQL issyntactically correct, only that there are no unclosed string literals and thestatement is terminated by a semicolon.This can be used to build a shell for SQLite, as in the following example:
# A minimal SQLite shell for experimentsimportsqlite3con=sqlite3.connect(":memory:")con.isolation_level=Nonecur=con.cursor()buffer=""print("Enter your SQL commands to execute in sqlite3.")print("Enter a blank line to exit.")whileTrue:line=input()ifline=="":breakbuffer+=lineifsqlite3.complete_statement(buffer):try:buffer=buffer.strip()cur.execute(buffer)ifbuffer.lstrip().upper().startswith("SELECT"):print(cur.fetchall())exceptsqlite3.Errorase:print("An error occurred:",e.args[0])buffer=""con.close()
sqlite3.enable_callback_tracebacks(flag)¶By default you will not get any tracebacks in user-defined functions,aggregates, converters, authorizer callbacks etc. If you want to debug them,you can call this function withflag set to
True. Afterwards, you willget tracebacks from callbacks onsys.stderr. UseFalsetodisable the feature again.
Connection Objects¶
- class
sqlite3.Connection¶ An SQLite database connection has the following attributes and methods:
isolation_level¶Get or set the current default isolation level.
Nonefor autocommit mode orone of “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”. See sectionControlling Transactions for a more detailed explanation.
in_transaction¶Trueif a transaction is active (there are uncommitted changes),Falseotherwise. Read-only attribute.New in version 3.2.
cursor(factory=Cursor)¶The cursor method accepts a single optional parameterfactory. Ifsupplied, this must be a callable returning an instance of
Cursoror its subclasses.
commit()¶This method commits the current transaction. If you don’t call this method,anything you did since the last call to
commit()is not visible fromother database connections. If you wonder why you don’t see the data you’vewritten to the database, please check you didn’t forget to call this method.
close()¶This closes the database connection. Note that this does not automaticallycall
commit(). If you just close your database connection withoutcallingcommit()first, your changes will be lost!
execute(sql[,parameters])¶Create a new
Cursorobject and callexecute()on it with the givensql andparameters.Return the new cursor object.
executemany(sql[,parameters])¶Create a new
Cursorobject and callexecutemany()on it with the givensql andparameters.Return the new cursor object.
executescript(sql_script)¶Create a new
Cursorobject and callexecutescript()on it with the givensql_script.Return the new cursor object.
create_function(name,num_params,func,*,deterministic=False)¶Creates a user-defined function that you can later use from within SQLstatements under the function namename.num_params is the number ofparameters the function accepts (ifnum_params is -1, the function maytake any number of arguments), andfunc is a Python callable that iscalled as the SQL function. Ifdeterministic is true, the created functionis marked asdeterministic, whichallows SQLite to perform additional optimizations. This flag is supported bySQLite 3.8.3 or higher,
NotSupportedErrorwill be raised if usedwith older versions.The function can return any of the types supported by SQLite: bytes, str, int,float and
None.Changed in version 3.8:Thedeterministic parameter was added.
Example:
importsqlite3importhashlibdefmd5sum(t):returnhashlib.md5(t).hexdigest()con=sqlite3.connect(":memory:")con.create_function("md5",1,md5sum)cur=con.cursor()cur.execute("select md5(?)",(b"foo",))print(cur.fetchone()[0])con.close()
create_aggregate(name,num_params,aggregate_class)¶Creates a user-defined aggregate function.
The aggregate class must implement a
stepmethod, which accepts the numberof parametersnum_params (ifnum_params is -1, the function may takeany number of arguments), and afinalizemethod which will return thefinal result of the aggregate.The
finalizemethod can return any of the types supported by SQLite:bytes, str, int, float andNone.Example:
importsqlite3classMySum:def__init__(self):self.count=0defstep(self,value):self.count+=valuedeffinalize(self):returnself.countcon=sqlite3.connect(":memory:")con.create_aggregate("mysum",1,MySum)cur=con.cursor()cur.execute("create table test(i)")cur.execute("insert into test(i) values (1)")cur.execute("insert into test(i) values (2)")cur.execute("select mysum(i) from test")print(cur.fetchone()[0])con.close()
create_collation(name,callable)¶Creates a collation with the specifiedname andcallable. The callable willbe passed two string arguments. It should return -1 if the first is orderedlower than the second, 0 if they are ordered equal and 1 if the first is orderedhigher than the second. Note that this controls sorting (ORDER BY in SQL) soyour comparisons don’t affect other SQL operations.
Note that the callable will get its parameters as Python bytestrings, which willnormally be encoded in UTF-8.
The following example shows a custom collation that sorts “the wrong way”:
importsqlite3defcollate_reverse(string1,string2):ifstring1==string2:return0elifstring1<string2:return1else:return-1con=sqlite3.connect(":memory:")con.create_collation("reverse",collate_reverse)cur=con.cursor()cur.execute("create table test(x)")cur.executemany("insert into test(x) values (?)",[("a",),("b",)])cur.execute("select x from test order by x collate reverse")forrowincur:print(row)con.close()
To remove a collation, call
create_collationwithNoneas callable:con.create_collation("reverse",None)
interrupt()¶You can call this method from a different thread to abort any queries that mightbe executing on the connection. The query will then abort and the caller willget an exception.
set_authorizer(authorizer_callback)¶This routine registers a callback. The callback is invoked for each attempt toaccess a column of a table in the database. The callback should return
SQLITE_OKif access is allowed,SQLITE_DENYif the entire SQLstatement should be aborted with an error andSQLITE_IGNOREif thecolumn should be treated as a NULL value. These constants are available in thesqlite3module.The first argument to the callback signifies what kind of operation is to beauthorized. The second and third argument will be arguments or
Nonedepending on the first argument. The 4th argument is the name of the database(“main”, “temp”, etc.) if applicable. The 5th argument is the name of theinner-most trigger or view that is responsible for the access attempt orNoneif this access attempt is directly from input SQL code.Please consult the SQLite documentation about the possible values for the firstargument and the meaning of the second and third argument depending on the firstone. All necessary constants are available in the
sqlite3module.
set_progress_handler(handler,n)¶This routine registers a callback. The callback is invoked for everyninstructions of the SQLite virtual machine. This is useful if you want toget called from SQLite during long-running operations, for example to updatea GUI.
If you want to clear any previously installed progress handler, call themethod with
Noneforhandler.Returning a non-zero value from the handler function will terminate thecurrently executing query and cause it to raise an
OperationalErrorexception.
set_trace_callback(trace_callback)¶Registerstrace_callback to be called for each SQL statement that isactually executed by the SQLite backend.
The only argument passed to the callback is the statement (as
str) that is being executed. The return value of the callback isignored. Note that the backend does not only run statements passed to theCursor.execute()methods. Other sources include thetransaction management of thesqlite3 module and the execution of triggers defined in the currentdatabase.Passing
Noneastrace_callback will disable the trace callback.Note
Exceptions raised in the trace callback are not propagated. As adevelopment and debugging aid, use
enable_callback_tracebacks()to enable printingtracebacks from exceptions raised in the trace callback.New in version 3.3.
enable_load_extension(enabled)¶This routine allows/disallows the SQLite engine to load SQLite extensionsfrom shared libraries. SQLite extensions can define new functions,aggregates or whole new virtual table implementations. One well-knownextension is the fulltext-search extension distributed with SQLite.
Loadable extensions are disabled by default. See1.
New in version 3.2.
importsqlite3con=sqlite3.connect(":memory:")# enable extension loadingcon.enable_load_extension(True)# Load the fulltext search extensioncon.execute("select load_extension('./fts3.so')")# alternatively you can load the extension using an API call:# con.load_extension("./fts3.so")# disable extension loading againcon.enable_load_extension(False)# example from SQLite wikicon.execute("create virtual table recipe using fts3(name, ingredients)")con.executescript(""" insert into recipe (name, ingredients) values ('broccoli stew', 'broccoli peppers cheese tomatoes'); insert into recipe (name, ingredients) values ('pumpkin stew', 'pumpkin onions garlic celery'); insert into recipe (name, ingredients) values ('broccoli pie', 'broccoli cheese onions flour'); insert into recipe (name, ingredients) values ('pumpkin pie', 'pumpkin sugar flour butter'); """)forrowincon.execute("select rowid, name, ingredients from recipe where name match 'pie'"):print(row)con.close()
load_extension(path)¶This routine loads an SQLite extension from a shared library. You have toenable extension loading with
enable_load_extension()before you canuse this routine.Loadable extensions are disabled by default. See1.
New in version 3.2.
row_factory¶You can change this attribute to a callable that accepts the cursor and theoriginal row as a tuple and will return the real result row. This way, you canimplement more advanced ways of returning results, such as returning an objectthat can also access columns by name.
Example:
importsqlite3defdict_factory(cursor,row):d={}foridx,colinenumerate(cursor.description):d[col[0]]=row[idx]returndcon=sqlite3.connect(":memory:")con.row_factory=dict_factorycur=con.cursor()cur.execute("select 1 as a")print(cur.fetchone()["a"])con.close()
If returning a tuple doesn’t suffice and you want name-based access tocolumns, you should consider setting
row_factoryto thehighly-optimizedsqlite3.Rowtype.Rowprovides bothindex-based and case-insensitive name-based access to columns with almost nomemory overhead. It will probably be better than your own customdictionary-based approach or even a db_row based solution.
text_factory¶Using this attribute you can control what objects are returned for the
TEXTdata type. By default, this attribute is set tostrand thesqlite3module will returnstrobjects forTEXT.If you want to returnbytesinstead, you can set it tobytes.You can also set it to any other callable that accepts a single bytestringparameter and returns the resulting object.
See the following example code for illustration:
importsqlite3con=sqlite3.connect(":memory:")cur=con.cursor()AUSTRIA="Österreich"# by default, rows are returned as strcur.execute("select ?",(AUSTRIA,))row=cur.fetchone()assertrow[0]==AUSTRIA# but we can make sqlite3 always return bytestrings ...con.text_factory=bytescur.execute("select ?",(AUSTRIA,))row=cur.fetchone()asserttype(row[0])isbytes# the bytestrings will be encoded in UTF-8, unless you stored garbage in the# database ...assertrow[0]==AUSTRIA.encode("utf-8")# we can also implement a custom text_factory ...# here we implement one that appends "foo" to all stringscon.text_factory=lambdax:x.decode("utf-8")+"foo"cur.execute("select ?",("bar",))row=cur.fetchone()assertrow[0]=="barfoo"con.close()
total_changes¶Returns the total number of database rows that have been modified, inserted, ordeleted since the database connection was opened.
iterdump()¶Returns an iterator to dump the database in an SQL text format. Useful whensaving an in-memory database for later restoration. This function providesthe same capabilities as the.dump command in thesqlite3shell.
Example:
# Convert file existing_db.db to SQL dump file dump.sqlimportsqlite3con=sqlite3.connect('existing_db.db')withopen('dump.sql','w')asf:forlineincon.iterdump():f.write('%s\n'%line)con.close()
backup(target,*,pages=-1,progress=None,name="main",sleep=0.250)¶This method makes a backup of an SQLite database even while it’s being accessedby other clients, or concurrently by the same connection. The copy will bewritten into the mandatory argumenttarget, that must be another
Connectioninstance.By default, or whenpages is either
0or a negative integer, the entiredatabase is copied in a single step; otherwise the method performs a loopcopying up topages pages at a time.Ifprogress is specified, it must either be
Noneor a callable object thatwill be executed at each iteration with three integer arguments, respectivelythestatus of the last iteration, theremaining number of pages still to becopied and thetotal number of pages.Thename argument specifies the database name that will be copied: it must bea string containing either
"main", the default, to indicate the maindatabase,"temp"to indicate the temporary database or the name specifiedafter theASkeyword in anATTACHDATABASEstatement for an attacheddatabase.Thesleep argument specifies the number of seconds to sleep by betweensuccessive attempts to backup remaining pages, can be specified either as aninteger or a floating point value.
Example 1, copy an existing database into another:
importsqlite3defprogress(status,remaining,total):print(f'Copied{total-remaining} of{total} pages...')con=sqlite3.connect('existing_db.db')bck=sqlite3.connect('backup.db')withbck:con.backup(bck,pages=1,progress=progress)bck.close()con.close()
Example 2, copy an existing database into a transient copy:
importsqlite3source=sqlite3.connect('existing_db.db')dest=sqlite3.connect(':memory:')source.backup(dest)
Availability: SQLite 3.6.11 or higher
New in version 3.7.
Cursor Objects¶
- class
sqlite3.Cursor¶ A
Cursorinstance has the following attributes and methods.execute(sql[,parameters])¶Executes an SQL statement. Values may be bound to the statement usingplaceholders.
execute()will only execute a single SQL statement. If you try to executemore than one statement with it, it will raise aWarning. Useexecutescript()if you want to execute multiple SQL statements with onecall.
executemany(sql,seq_of_parameters)¶Executes aparameterized SQL commandagainst all parameter sequences or mappings found in the sequenceseq_of_parameters. The
sqlite3module also allows using aniterator yielding parameters instead of a sequence.importsqlite3classIterChars:def__init__(self):self.count=ord('a')def__iter__(self):returnselfdef__next__(self):ifself.count>ord('z'):raiseStopIterationself.count+=1return(chr(self.count-1),)# this is a 1-tuplecon=sqlite3.connect(":memory:")cur=con.cursor()cur.execute("create table characters(c)")theIter=IterChars()cur.executemany("insert into characters(c) values (?)",theIter)cur.execute("select c from characters")print(cur.fetchall())con.close()
Here’s a shorter example using agenerator:
importsqlite3importstringdefchar_generator():forcinstring.ascii_lowercase:yield(c,)con=sqlite3.connect(":memory:")cur=con.cursor()cur.execute("create table characters(c)")cur.executemany("insert into characters(c) values (?)",char_generator())cur.execute("select c from characters")print(cur.fetchall())con.close()
executescript(sql_script)¶This is a nonstandard convenience method for executing multiple SQL statementsat once. It issues a
COMMITstatement first, then executes the SQL script itgets as a parameter. This method disregardsisolation_level; anytransaction control must be added tosql_script.sql_script can be an instance of
str.Example:
importsqlite3con=sqlite3.connect(":memory:")cur=con.cursor()cur.executescript(""" create table person( firstname, lastname, age ); create table book( title, author, published ); insert into book(title, author, published) values ( 'Dirk Gently''s Holistic Detective Agency', 'Douglas Adams', 1987 ); """)con.close()
fetchone()¶Fetches the next row of a query result set, returning a single sequence,or
Nonewhen no more data is available.
fetchmany(size=cursor.arraysize)¶Fetches the next set of rows of a query result, returning a list. An emptylist is returned when no more rows are available.
The number of rows to fetch per call is specified by thesize parameter.If it is not given, the cursor’s arraysize determines the number of rowsto be fetched. The method should try to fetch as many rows as indicated bythe size parameter. If this is not possible due to the specified number ofrows not being available, fewer rows may be returned.
Note there are performance considerations involved with thesize parameter.For optimal performance, it is usually best to use the arraysize attribute.If thesize parameter is used, then it is best for it to retain the samevalue from one
fetchmany()call to the next.
fetchall()¶Fetches all (remaining) rows of a query result, returning a list. Note thatthe cursor’s arraysize attribute can affect the performance of this operation.An empty list is returned when no rows are available.
close()¶Close the cursor now (rather than whenever
__del__is called).The cursor will be unusable from this point forward; a
ProgrammingErrorexception will be raised if any operation is attempted with the cursor.
rowcount¶Although the
Cursorclass of thesqlite3module implements thisattribute, the database engine’s own support for the determination of “rowsaffected”/”rows selected” is quirky.For
executemany()statements, the number of modifications are summed upintorowcount.As required by the Python DB API Spec, the
rowcountattribute “is -1 incase noexecuteXX()has been performed on the cursor or the rowcount of thelast operation is not determinable by the interface”. This includesSELECTstatements because we cannot determine the number of rows a query produceduntil all rows were fetched.With SQLite versions before 3.6.5,
rowcountis set to 0 ifyou make aDELETEFROMtablewithout any condition.
lastrowid¶This read-only attribute provides the row id of the last inserted row. Itis only updated after successful
INSERTorREPLACEstatementsusing theexecute()method. For other statements, afterexecutemany()orexecutescript(), or if the insertion failed,the value oflastrowidis left unchanged. The initial value oflastrowidisNone.Note
Inserts into
WITHOUTROWIDtables are not recorded.Changed in version 3.6:Added support for the
REPLACEstatement.
arraysize¶Read/write attribute that controls the number of rows returned by
fetchmany().The default value is 1 which means a single row would be fetched per call.
description¶This read-only attribute provides the column names of the last query. Toremain compatible with the Python DB API, it returns a 7-tuple for eachcolumn where the last six items of each tuple are
None.It is set for
SELECTstatements without any matching rows as well.
connection¶This read-only attribute provides the SQLite database
Connectionused by theCursorobject. ACursorobject created bycallingcon.cursor()will have aconnectionattribute that refers tocon:>>>con=sqlite3.connect(":memory:")>>>cur=con.cursor()>>>cur.connection==conTrue
Row Objects¶
- class
sqlite3.Row¶ A
Rowinstance serves as a highly optimizedrow_factoryforConnectionobjects.It tries to mimic a tuple in most of its features.It supports mapping access by column name and index, iteration,representation, equality testing and
len().If two
Rowobjects have exactly the same columns and theirmembers are equal, they compare equal.keys()¶This method returns a list of column names. Immediately after a query,it is the first member of each tuple in
Cursor.description.
Changed in version 3.5:Added support of slicing.
Let’s assume we initialize a table as in the example given above:
con=sqlite3.connect(":memory:")cur=con.cursor()cur.execute('''create table stocks(date text, trans text, symbol text, qty real, price real)''')cur.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")con.commit()cur.close()
Now we plugRow in:
>>>con.row_factory=sqlite3.Row>>>cur=con.cursor()>>>cur.execute('select * from stocks')<sqlite3.Cursor object at 0x7f4e7dd8fa80>>>>r=cur.fetchone()>>>type(r)<class 'sqlite3.Row'>>>>tuple(r)('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)>>>len(r)5>>>r[2]'RHAT'>>>r.keys()['date', 'trans', 'symbol', 'qty', 'price']>>>r['qty']100.0>>>formemberinr:...print(member)...2006-01-05BUYRHAT100.035.14
Exceptions¶
- exception
sqlite3.Error¶ The base class of the other exceptions in this module. It is a subclassof
Exception.
- exception
sqlite3.DatabaseError¶ Exception raised for errors that are related to the database.
- exception
sqlite3.IntegrityError¶ Exception raised when the relational integrity of the database is affected,e.g. a foreign key check fails. It is a subclass of
DatabaseError.
- exception
sqlite3.ProgrammingError¶ Exception raised for programming errors, e.g. table not found or alreadyexists, syntax error in the SQL statement, wrong number of parametersspecified, etc. It is a subclass of
DatabaseError.
- exception
sqlite3.OperationalError¶ Exception raised for errors that are related to the database’s operationand not necessarily under the control of the programmer, e.g. an unexpecteddisconnect occurs, the data source name is not found, a transaction couldnot be processed, etc. It is a subclass of
DatabaseError.
- exception
sqlite3.NotSupportedError¶ Exception raised in case a method or database API was used which is notsupported by the database, e.g. calling the
rollback()method on a connection that does not support transaction or hastransactions turned off. It is a subclass ofDatabaseError.
SQLite and Python types¶
Introduction¶
SQLite natively supports the following types:NULL,INTEGER,REAL,TEXT,BLOB.
The following Python types can thus be sent to SQLite without any problem:
Python type | SQLite type |
|---|---|
| |
| |
| |
| |
|
This is how SQLite types are converted to Python types by default:
SQLite type | Python type |
|---|---|
| |
| |
| |
| depends on |
|
The type system of thesqlite3 module is extensible in two ways: you canstore additional Python types in an SQLite database via object adaptation, andyou can let thesqlite3 module convert SQLite types to different Pythontypes via converters.
Using adapters to store additional Python types in SQLite databases¶
As described before, SQLite supports only a limited set of types natively. Touse other Python types with SQLite, you mustadapt them to one of thesqlite3 module’s supported types for SQLite: one of NoneType, int, float,str, bytes.
There are two ways to enable thesqlite3 module to adapt a custom Pythontype to one of the supported ones.
Letting your object adapt itself¶
This is a good approach if you write the class yourself. Let’s suppose you havea class like this:
classPoint:def__init__(self,x,y):self.x,self.y=x,y
Now you want to store the point in a single SQLite column. First you’ll have tochoose one of the supported types to be used for representing the point.Let’s just use str and separate the coordinates using a semicolon. Then you needto give your class a method__conform__(self,protocol) which must returnthe converted value. The parameterprotocol will bePrepareProtocol.
importsqlite3classPoint:def__init__(self,x,y):self.x,self.y=x,ydef__conform__(self,protocol):ifprotocolissqlite3.PrepareProtocol:return"%f;%f"%(self.x,self.y)con=sqlite3.connect(":memory:")cur=con.cursor()p=Point(4.0,-3.2)cur.execute("select ?",(p,))print(cur.fetchone()[0])con.close()
Registering an adapter callable¶
The other possibility is to create a function that converts the type to thestring representation and register the function withregister_adapter().
importsqlite3classPoint:def__init__(self,x,y):self.x,self.y=x,ydefadapt_point(point):return"%f;%f"%(point.x,point.y)sqlite3.register_adapter(Point,adapt_point)con=sqlite3.connect(":memory:")cur=con.cursor()p=Point(4.0,-3.2)cur.execute("select ?",(p,))print(cur.fetchone()[0])con.close()
Thesqlite3 module has two default adapters for Python’s built-indatetime.date anddatetime.datetime types. Now let’s supposewe want to storedatetime.datetime objects not in ISO representation,but as a Unix timestamp.
importsqlite3importdatetimeimporttimedefadapt_datetime(ts):returntime.mktime(ts.timetuple())sqlite3.register_adapter(datetime.datetime,adapt_datetime)con=sqlite3.connect(":memory:")cur=con.cursor()now=datetime.datetime.now()cur.execute("select ?",(now,))print(cur.fetchone()[0])con.close()
Converting SQLite values to custom Python types¶
Writing an adapter lets you send custom Python types to SQLite. But to make itreally useful we need to make the Python to SQLite to Python roundtrip work.
Enter converters.
Let’s go back to thePoint class. We stored the x and y coordinatesseparated via semicolons as strings in SQLite.
First, we’ll define a converter function that accepts the string as a parameterand constructs aPoint object from it.
Note
Converter functionsalways get called with abytes object, nomatter under which data type you sent the value to SQLite.
defconvert_point(s):x,y=map(float,s.split(b";"))returnPoint(x,y)
Now you need to make thesqlite3 module know that what you select fromthe database is actually a point. There are two ways of doing this:
Implicitly via the declared type
Explicitly via the column name
Both ways are described in sectionModule functions and constants, in the entriesfor the constantsPARSE_DECLTYPES andPARSE_COLNAMES.
The following example illustrates both approaches.
importsqlite3classPoint:def__init__(self,x,y):self.x,self.y=x,ydef__repr__(self):return"(%f;%f)"%(self.x,self.y)defadapt_point(point):return("%f;%f"%(point.x,point.y)).encode('ascii')defconvert_point(s):x,y=list(map(float,s.split(b";")))returnPoint(x,y)# Register the adaptersqlite3.register_adapter(Point,adapt_point)# Register the convertersqlite3.register_converter("point",convert_point)p=Point(4.0,-3.2)########################## 1) Using declared typescon=sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_DECLTYPES)cur=con.cursor()cur.execute("create table test(p point)")cur.execute("insert into test(p) values (?)",(p,))cur.execute("select p from test")print("with declared types:",cur.fetchone()[0])cur.close()con.close()######################## 1) Using column namescon=sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_COLNAMES)cur=con.cursor()cur.execute("create table test(p)")cur.execute("insert into test(p) values (?)",(p,))cur.execute('select p as "p [point]" from test')print("with column names:",cur.fetchone()[0])cur.close()con.close()
Default adapters and converters¶
There are default adapters for the date and datetime types in the datetimemodule. They will be sent as ISO dates/ISO timestamps to SQLite.
The default converters are registered under the name “date” fordatetime.date and under the name “timestamp” fordatetime.datetime.
This way, you can use date/timestamps from Python without any additionalfiddling in most cases. The format of the adapters is also compatible with theexperimental SQLite date/time functions.
The following example demonstrates this.
importsqlite3importdatetimecon=sqlite3.connect(":memory:",detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)cur=con.cursor()cur.execute("create table test(d date, ts timestamp)")today=datetime.date.today()now=datetime.datetime.now()cur.execute("insert into test(d, ts) values (?, ?)",(today,now))cur.execute("select d, ts from test")row=cur.fetchone()print(today,"=>",row[0],type(row[0]))print(now,"=>",row[1],type(row[1]))cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]"')row=cur.fetchone()print("current_date",row[0],type(row[0]))print("current_timestamp",row[1],type(row[1]))con.close()
If a timestamp stored in SQLite has a fractional part longer than 6numbers, its value will be truncated to microsecond precision by thetimestamp converter.
Note
The default “timestamp” converter ignores UTC offsets in the database andalways returns a naivedatetime.datetime object. To preserve UTCoffsets in timestamps, either leave converters disabled, or register anoffset-aware converter withregister_converter().
Controlling Transactions¶
The underlyingsqlite3 library operates inautocommit mode by default,but the Pythonsqlite3 module by default does not.
autocommit mode means that statements that modify the database take effectimmediately. ABEGIN orSAVEPOINT statement disablesautocommitmode, and aCOMMIT, aROLLBACK, or aRELEASE that ends theoutermost transaction, turnsautocommit mode back on.
The Pythonsqlite3 module by default issues aBEGIN statementimplicitly before a Data Modification Language (DML) statement (i.e.INSERT/UPDATE/DELETE/REPLACE).
You can control which kind ofBEGIN statementssqlite3 implicitlyexecutes via theisolation_level parameter to theconnect()call, or via theisolation_level property of connections.If you specify noisolation_level, a plainBEGIN is used, which isequivalent to specifyingDEFERRED. Other possible values areIMMEDIATEandEXCLUSIVE.
You can disable thesqlite3 module’s implicit transaction management bysettingisolation_level toNone. This will leave the underlyingsqlite3 library operating inautocommit mode. You can then completelycontrol the transaction state by explicitly issuingBEGIN,ROLLBACK,SAVEPOINT, andRELEASE statements in your code.
Note thatexecutescript() disregardsisolation_level; any transaction control must be added explicitly.
Changed in version 3.6:sqlite3 used to implicitly commit an open transaction before DDLstatements. This is no longer the case.
Usingsqlite3 efficiently¶
Using shortcut methods¶
Using the nonstandardexecute(),executemany() andexecutescript() methods of theConnection object, your code canbe written more concisely because you don’t have to create the (oftensuperfluous)Cursor objects explicitly. Instead, theCursorobjects are created implicitly and these shortcut methods return the cursorobjects. This way, you can execute aSELECT statement and iterate over itdirectly using only a single call on theConnection object.
importsqlite3langs=[("C++",1985),("Objective-C",1984),]con=sqlite3.connect(":memory:")# Create the tablecon.execute("create table lang(name, first_appeared)")# Fill the tablecon.executemany("insert into lang(name, first_appeared) values (?, ?)",langs)# Print the table contentsforrowincon.execute("select name, first_appeared from lang"):print(row)print("I just deleted",con.execute("delete from lang").rowcount,"rows")# close is not a shortcut method and it's not called automatically,# so the connection object should be closed manuallycon.close()
Accessing columns by name instead of by index¶
One useful feature of thesqlite3 module is the built-insqlite3.Row class designed to be used as a row factory.
Rows wrapped with this class can be accessed both by index (like tuples) andcase-insensitively by name:
importsqlite3con=sqlite3.connect(":memory:")con.row_factory=sqlite3.Rowcur=con.cursor()cur.execute("select 'John' as name, 42 as age")forrowincur:assertrow[0]==row["name"]assertrow["name"]==row["nAmE"]assertrow[1]==row["age"]assertrow[1]==row["AgE"]con.close()
Using the connection as a context manager¶
Connection objects can be used as context managersthat automatically commit or rollback transactions. In the event of anexception, the transaction is rolled back; otherwise, the transaction iscommitted:
importsqlite3con=sqlite3.connect(":memory:")con.execute("create table lang (id integer primary key, name varchar unique)")# Successful, con.commit() is called automatically afterwardswithcon:con.execute("insert into lang(name) values (?)",("Python",))# con.rollback() is called after the with block finishes with an exception, the# exception is still raised and must be caughttry:withcon:con.execute("insert into lang(name) values (?)",("Python",))exceptsqlite3.IntegrityError:print("couldn't add Python twice")# Connection object used as context manager only commits or rollbacks transactions,# so the connection object should be closed manuallycon.close()
Footnotes