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.
sqlite3 was written by Gerhard Häring and provides a SQL interface compliantwith the DB-API 2.0 specification described byPEP 249.
To use the module, you must first create aConnection object thatrepresents the database. Here the data will be stored in theexample.db file:
importsqlite3conn=sqlite3.connect('example.db')
You can also supply the special name:memory: to create a database in RAM.
Once you have aConnection, you can create aCursor objectand call itsexecute() method to perform SQL commands:
c=conn.cursor()# Create tablec.execute('''create table stocks(date text, trans text, symbol text, qty real, price real)''')# Insert a row of datac.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")# Save (commit) the changesconn.commit()# We can also close the cursor if we are done with itc.close()
Usually your SQL operations will need to use values from Python variables. Youshouldn’t assemble your query using Python’s string operations because doing sois insecure; it makes your program vulnerable to an SQL injection attack.
Instead, use the DB-API’s parameter substitution. Put? as a placeholderwherever you want to use a value, and then provide a tuple of values as thesecond argument to the cursor’sexecute() method. (Other databasemodules may use a different placeholder, such as%s or:1.) Forexample:
# Never do this -- insecure!symbol='IBM'c.execute("select * from stocks where symbol = '%s'"%symbol)# Do this insteadt=('IBM',)c.execute('select * from stocks where symbol=?',t)# Larger examplefortin[('2006-03-28','BUY','IBM',1000,45.00),('2006-04-05','BUY','MSFT',1000,72.00),('2006-04-06','SELL','IBM',500,53.00),]:c.execute('insert into stocks values (?,?,?,?,?)',t)
To retrieve data after executing a SELECT statement, you can either treat thecursor as aniterator, call the cursor’sfetchone() method toretrieve a single matching row, or callfetchall() to get a list of thematching rows.
This example uses the iterator form:
>>>c=conn.cursor()>>>c.execute('select * from stocks order by price')>>>forrowinc:...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', 'MSOFT', 1000, 72.0)>>>
See also
The version number of this module, as a string. This is not the version ofthe SQLite library.
The version number of this module, as a tuple of integers. This is not theversion of the SQLite library.
The version number of the run-time SQLite library, as a string.
The version number of the run-time SQLite library, as a tuple of integers.
This constant is meant to be used with thedetect_types parameter of theconnect() function.
Setting it makes thesqlite3 module 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.
This constant is meant to be used with thedetect_types parameter of theconnect() 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 inCursor.descriptionis only the first word of the column name, i. e. if you use something like'as"x[datetime]"' in your SQL, then we will parse out everything until thefirst blank for the column name: the column name would simply be “x”.
Opens a connection to the SQLite database filedatabase. You can use":memory:" to open a database connection to a database that resides in RAMinstead 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 theConnection.isolation_level property ofConnection objects.
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-levelregister_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 ofPARSE_DECLTYPES andPARSE_COLNAMES to turntype detection on.
By default, thesqlite3 module uses itsConnection class for theconnect call. You can, however, subclass theConnection class and makeconnect() use your class instead by providing your class for thefactoryparameter.
Consult the sectionSQLite and Python types of this manual for details.
Thesqlite3 module 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.
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 theconnect()function for how the type detection works. Note that the case oftypename andthe name of the type in your query must match!
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.
ReturnsTrue if 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()
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 toTrue. Afterwards, you willget tracebacks from callbacks onsys.stderr. UseFalse todisable the feature again.
A SQLite database connection has the following attributes and methods:
Get or set the current isolation level.None for autocommit mode orone of “DEFERRED”, “IMMEDIATE” or “EXCLUSIVE”. See sectionControlling Transactions for a more detailed explanation.
True if a transaction is active (there are uncommitted changes),False otherwise. Read-only attribute.
New in version 3.2.
The cursor method accepts a single optional parametercursorClass. Ifsupplied, this must be a custom cursor class that extendssqlite3.Cursor.
This method commits the current transaction. If you don’t call this method,anything you did since the last call tocommit() 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.
This closes the database connection. Note that this does not automaticallycallcommit(). If you just close your database connection withoutcallingcommit() first, your changes will be lost!
This is a nonstandard shortcut that creates an intermediate cursor object bycalling the cursor method, then calls the cursor’sexecute method with the parameters given.
This is a nonstandard shortcut that creates an intermediate cursor object bycalling the cursor method, then calls the cursor’sexecutemany method with the parameters given.
This is a nonstandard shortcut that creates an intermediate cursor object bycalling the cursor method, then calls the cursor’sexecutescript method with the parameters given.
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, andfunc is a Python callable that is calledas the SQL function.
The function can return any of the types supported by SQLite: bytes, str, int,float and None.
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])
Creates a user-defined aggregate function.
The aggregate class must implement astep method, which accepts the numberof parametersnum_params, and afinalize method which will return thefinal result of the aggregate.
Thefinalize method can return any of the types supported by SQLite:bytes, str, int, float and None.
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])
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, callcreate_collation with None as callable:
con.create_collation("reverse",None)
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.
This routine registers a callback. The callback is invoked for each attempt toaccess a column of a table in the database. The callback should returnSQLITE_OK if access is allowed,SQLITE_DENY if the entire SQLstatement should be aborted with an error andSQLITE_IGNORE if thecolumn should be treated as a NULL value. These constants are available in thesqlite3 module.
The first argument to the callback signifies what kind of operation is to beauthorized. The second and third argument will be arguments orNonedepending 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 orNone if 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 thesqlite3 module.
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 withNone forhandler.
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 string) thatis being executed. The return value of the callback is ignored. Note thatthe backend does not only run statements passed to theCursor.execute()methods. Other sources include the transaction management of the Pythonmodule and the execution of triggers defined in the current database.
PassingNone astrace_callback will disable the trace callback.
New in version 3.3.
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. See[1].
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 laoding 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)
This routine loads a SQLite extension from a shared library. You have toenable extension loading withenable_load_extension() before you canuse this routine.
Loadable extensions are disabled by default. See[1].
New in version 3.2.
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"])
If returning a tuple doesn’t suffice and you want name-based access tocolumns, you should consider settingrow_factory to thehighly-optimizedsqlite3.Row type.Row provides 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.
Using this attribute you can control what objects are returned for theTEXTdata type. By default, this attribute is set tostr and thesqlite3 module will return Unicode objects forTEXT. If you want toreturn bytestrings instead, you can set it tobytes.
For efficiency reasons, there’s also a way to returnstr objectsonly for non-ASCII data, andbytes otherwise. To activate it, setthis attribute tosqlite3.OptimizedUnicode.
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="\xd6sterreich"# by default, rows are returned as Unicodecur.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"
Returns the total number of database rows that have been modified, inserted, ordeleted since the database connection was opened.
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.sqlimportsqlite3,oscon=sqlite3.connect('existing_db.db')withopen('dump.sql','w')asf:forlineincon.iterdump():f.write('%s\n'%line)
ACursor instance has the following attributes and methods.
Executes an SQL statement. The SQL statement may be parametrized (i. e.placeholders instead of SQL literals). Thesqlite3 module supports twokinds of placeholders: question marks (qmark style) and named placeholders(named style).
Here’s an example of both styles:
importsqlite3con=sqlite3.connect(":memory:")cur=con.cursor()cur.execute("create table people (name_last, age)")who="Yeltsin"age=72# This is the qmark style:cur.execute("insert into people values (?, ?)",(who,age))# And this is the named style:cur.execute("select * from people where name_last=:who and age=:age",{"who":who,"age":age})print(cur.fetchone())
execute() will only execute a single SQL statement. If you try to executemore than one statement with it, it will raise a Warning. Useexecutescript() if you want to execute multiple SQL statements with onecall.
Executes an SQL command against all parameter sequences or mappings found inthe sequencesql. Thesqlite3 module 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())
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())
This is a nonstandard convenience method for executing multiple SQL statementsat once. It issues aCOMMIT statement first, then executes the SQL script itgets as a parameter.
sql_script can be an instance ofstr orbytes.
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 ); """)
Fetches the next row of a query result set, returning a single sequence,orNone when no more data is available.
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 onefetchmany() call to the next.
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.
Although theCursor class of thesqlite3 module implements thisattribute, the database engine’s own support for the determination of “rowsaffected”/”rows selected” is quirky.
Forexecutemany() statements, the number of modifications are summed upintorowcount.
As required by the Python DB API Spec, therowcount attribute “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,rowcount is set to 0 ifyou make aDELETEFROMtable without any condition.
This read-only attribute provides the rowid of the last modified row. It isonly set if you issued aINSERT statement using theexecute()method. For operations other thanINSERT or whenexecutemany() iscalled,lastrowid is set toNone.
ARow instance serves as a highly optimizedrow_factory forConnection objects.It tries to mimic a tuple in most of its features.
It supports mapping access by column name and index, iteration,representation, equality testing andlen().
If twoRow objects have exactly the same columns and theirmembers are equal, they compare equal.
This method returns a tuple of column names. Immediately after a query,it is the first member of each tuple inCursor.description.
Let’s assume we initialize a table as in the example given above:
conn=sqlite3.connect(":memory:")c=conn.cursor()c.execute('''create table stocks(date text, trans text, symbol text, qty real, price real)''')c.execute("""insert into stocks values ('2006-01-05','BUY','RHAT',100,35.14)""")conn.commit()c.close()
Now we plugRow in:
>>>conn.row_factory=sqlite3.Row>>>c=conn.cursor()>>>c.execute('select * from stocks')<sqlite3.Cursor object at 0x7f4e7dd8fa80>>>>r=c.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
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 |
|---|---|
| None | NULL |
| int | INTEGER |
| float | REAL |
| str | TEXT |
| bytes | BLOB |
This is how SQLite types are converted to Python types by default:
| SQLite type | Python type |
|---|---|
| NULL | None |
| INTEGER | int |
| REAL | float |
| TEXT | depends on text_factory, str by default |
| BLOB | bytes |
The type system of thesqlite3 module is extensible in two ways: you canstore additional Python types in a SQLite database via object adaptation, andyou can let thesqlite3 module convert SQLite types to different Pythontypes via converters.
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.
Thesqlite3 module uses Python object adaptation, as described inPEP 246 for this. The protocol to use isPrepareProtocol.
There are two ways to enable thesqlite3 module to adapt a custom Pythontype to one of the supported ones.
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 first 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])
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])
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])
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 a string, no matter under whichdata 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:
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()
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]))
If a timestamp stored in SQLite has a fractional part longer than 6numbers, its value will be truncated to microsecond precision by thetimestamp converter.
By default, thesqlite3 module opens transactions implicitly before aData Modification Language (DML) statement (i.e.INSERT/UPDATE/DELETE/REPLACE), and commits transactionsimplicitly before a non-DML, non-query statement (i. e.anything other thanSELECT or the aforementioned).
So if you are within a transaction and issue a command likeCREATETABLE...,VACUUM,PRAGMA, thesqlite3 module will commit implicitlybefore executing that command. There are two reasons for doing that. The firstis that some of these commands don’t work within transactions. The other reasonis that sqlite3 needs to keep track of the transaction state (if a transactionis active or not). The current transaction state is exposed through theConnection.in_transaction attribute of the connection object.
You can control which kind ofBEGIN statements sqlite3 implicitly executes(or none at all) via theisolation_level parameter to theconnect()call, or via theisolation_level property of connections.
If you wantautocommit mode, then setisolation_level to None.
Otherwise leave it at its default, which will result in a plain “BEGIN”statement, or set it to one of SQLite’s supported isolation levels: “DEFERRED”,“IMMEDIATE” or “EXCLUSIVE”.
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.
importsqlite3persons=[("Hugo","Boss"),("Calvin","Klein")]con=sqlite3.connect(":memory:")# Create the tablecon.execute("create table person(firstname, lastname)")# Fill the tablecon.executemany("insert into person(firstname, lastname) values (?, ?)",persons)# Print the table contentsforrowincon.execute("select firstname, lastname from person"):print(row)print("I just deleted",con.execute("delete from person").rowcount,"rows")
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"]
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 person (id integer primary key, firstname varchar unique)")# Successful, con.commit() is called automatically afterwardswithcon:con.execute("insert into person(firstname) values (?)",("Joe",))# 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 person(firstname) values (?)",("Joe",))exceptsqlite3.IntegrityError:print("couldn't add Joe twice")
Older SQLite versions had issues with sharing connections between threads.That’s why the Python module disallows sharing connections and cursors betweenthreads. If you still try to do so, you will get an exception at runtime.
The only exception is calling theinterrupt() method, whichonly makes sense to call from a different thread.
Footnotes
| [1] | (1,2) The sqlite3 module is not built with loadable extension support bydefault, because some platforms (notably Mac OS X) have SQLitelibraries which are compiled without this feature. To get loadableextension support, you must pass –enable-loadable-sqlite-extensions toconfigure. |
12.5.dbm — Interfaces to Unix “databases”
13. Data Compression and Archiving
Enter search terms or a module, class or function name.