sqlite3
--- SQLite 數據庫 DB-API 2.0 接口模塊?
源代碼: Lib/sqlite3/
SQLite 是一個(gè)C語(yǔ)言庫,它可以提供一種輕量級的基于磁盤(pán)的數據庫,這種數據庫不需要獨立的服務(wù)器進(jìn)程,也允許需要使用一種非標準的 SQL 查詢(xún)語(yǔ)言來(lái)訪(fǎng)問(wèn)它。一些應用程序可以使用 SQLite 作為內部數據存儲??梢杂盟鼇?lái)創(chuàng )建一個(gè)應用程序原型,然后再遷移到更大的數據庫,比如 PostgreSQL 或 Oracle。
The sqlite3 module was written by Gerhard H?ring. It provides an SQL interface compliant with the DB-API 2.0 specification described by PEP 249, and requires SQLite 3.7.15 or newer.
To use the module, start by creating a Connection
object that
represents the database. Here the data will be stored in the
example.db
file:
import sqlite3
con = sqlite3.connect('example.db')
The special path name :memory:
can be provided to create a temporary
database in RAM.
Once a Connection
has been established, create a Cursor
object
and call its execute()
method to perform SQL commands:
cur = con.cursor()
# Create table
cur.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
cur.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
# Save (commit) the changes
con.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 even after restarting the Python interpreter:
import sqlite3
con = sqlite3.connect('example.db')
cur = con.cursor()
To retrieve data after executing a SELECT statement, either treat the cursor as
an iterator, call the cursor's fetchone()
method to
retrieve a single matching row, or call fetchall()
to get a list
of the matching rows.
下面是一個(gè)使用迭代器形式的例子:
>>> for row in cur.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 they are vulnerable to SQL injection attacks (see the xkcd 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 a
query string, use a placeholder in the string, and substitute the actual values
into the query by providing them as a tuple
of values to the second
argument of the cursor's execute()
method. An SQL statement may
use one of two kinds of placeholders: question marks (qmark style) or named
placeholders (named style). For the qmark style, parameters
must be a
sequence. For the named style, it can be either a
sequence or dict
instance. The length of the
sequence must match the number of placeholders, or a
ProgrammingError
is raised. If a dict
is given, it must contain
keys for all named parameters. Any extra items are ignored. Here's an example of
both styles:
import sqlite3
con = 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()
參見(jiàn)
- https://www.sqlite.org
SQLite的主頁(yè);它的文檔詳細描述了它所支持的 SQL 方言的語(yǔ)法和可用的數據類(lèi)型。
- https://www.w3schools.com/sql/
學(xué)習 SQL 語(yǔ)法的教程、參考和例子。
- PEP 249 - DB-API 2.0 規范
PEP 由 Marc-André Lemburg 撰寫(xiě)。
模塊函數和常量?
- 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 by the
sqlite3
module. Required by the DB-API. Hard-coded to"qmark"
.備注
The
sqlite3
module supports bothqmark
andnumeric
DB-API parameter styles, because that is what the underlying SQLite library supports. However, the DB-API does not allow multiple values for theparamstyle
attribute.
- sqlite3.version?
這個(gè)模塊的版本號,是一個(gè)字符串。不是 SQLite 庫的版本號。
- sqlite3.version_info?
這個(gè)模塊的版本號,是一個(gè)由整數組成的元組。不是 SQLite 庫的版本號。
- sqlite3.sqlite_version?
使用中的 SQLite 庫的版本號,是一個(gè)字符串。
- sqlite3.sqlite_version_info?
使用中的 SQLite 庫的版本號,是一個(gè)整數組成的元組。
- sqlite3.threadsafety?
Integer constant required by the DB-API 2.0, stating the level of thread safety the
sqlite3
module supports. This attribute is set based on the default threading mode the underlying SQLite library is compiled with. The SQLite threading modes are:Single-thread: In this mode, all mutexes are disabled and SQLite is unsafe to use in more than a single thread at once.
Multi-thread: In this mode, SQLite can be safely used by multiple threads provided that no single database connection is used simultaneously in two or more threads.
Serialized: In serialized mode, SQLite can be safely used by multiple threads with no restriction.
The mappings from SQLite threading modes to DB-API 2.0 threadsafety levels are as follows:
SQLite threading mode
DB-API 2.0 meaning
single-thread
0
0
Threads may not share the module
multi-thread
1
2
Threads may share the module, but not connections
serialized
3
1
Threads may share the module, connections and cursors
在 3.11 版更改: Set threadsafety dynamically instead of hard-coding it to
1
.
- sqlite3.PARSE_DECLTYPES?
這個(gè)常量可以作為
connect()
函數的 detect_types 參數。設置這個(gè)參數后,
sqlite3
模塊將解析它返回的每一列申明的類(lèi)型。它會(huì )申明的類(lèi)型的第一個(gè)單詞,比如“integer primary key”,它會(huì )解析出“integer”,再比如“number(10)”,它會(huì )解析出“number”。然后,它會(huì )在轉換器字典里查找那個(gè)類(lèi)型注冊的轉換器函數,并調用它。
- sqlite3.PARSE_COLNAMES?
這個(gè)常量可以作為
connect()
函數的 detect_types 參數。設置此參數可使得 SQLite 接口解析它所返回的每一列的列名。 它將在其中查找形式為 [mytype] 的字符串,然后將 'mytype' 確定為列的類(lèi)型。 它將嘗試在轉換器字典中查找 'mytype' 條目,然后用找到的轉換器函數來(lái)返回值。 在
Cursor.description
中找到的列名并不包括類(lèi)型,舉例來(lái)說(shuō),如果你在你的 SQL 中使用了像'as "Expiration date [datetime]"'
這樣的寫(xiě)法,那么我們將解析出在第一個(gè)'['
之前的所有內容并去除前導空格作為列名:即列名將為 "Expiration date"。
- sqlite3.connect(database[, timeout, detect_types, isolation_level, check_same_thread, factory, cached_statements, uri])?
連接 SQLite 數據庫 database。默認返回
Connection
對象,除非使用了自定義的 factory 參數。database 是準備打開(kāi)的數據庫文件的路徑(絕對路徑或相對于當前目錄的相對路徑),它是 path-like object。你也可以用
":memory:"
在內存中打開(kāi)一個(gè)數據庫。當一個(gè)數據庫被多個(gè)連接訪(fǎng)問(wèn)的時(shí)候,如果其中一個(gè)進(jìn)程修改這個(gè)數據庫,在這個(gè)事務(wù)提交之前,這個(gè) SQLite 數據庫將會(huì )被一直鎖定。timeout 參數指定了這個(gè)連接等待鎖釋放的超時(shí)時(shí)間,超時(shí)之后會(huì )引發(fā)一個(gè)異常。這個(gè)超時(shí)時(shí)間默認是 5.0(5秒)。
isolation_level 參數,請查看
Connection
對象的isolation_level
屬性。SQLite 原生只支持5種類(lèi)型:TEXT,INTEGER,REAL,BLOB 和 NULL。如果你想用其它類(lèi)型,你必須自己添加相應的支持。使用 detect_types 參數和模塊級別的
register_converter()
函數注冊**轉換器** 可以簡(jiǎn)單的實(shí)現。detect_types 默認為 0 (即關(guān)閉,不進(jìn)行類(lèi)型檢測),你可以將其設為任意的
PARSE_DECLTYPES
和PARSE_COLNAMES
組合來(lái)啟用類(lèi)型檢測。 由于 SQLite 的行為,生成的字段類(lèi)型 (例如max(data)
) 不能被檢測,即使在設置了 detect_types 形參時(shí)也是如此。 在此情況下,返回的類(lèi)型為str
。默認情況下,check_same_thread 為
True
,只有當前的線(xiàn)程可以使用該連接。 如果設置為False
,則多個(gè)線(xiàn)程可以共享返回的連接。 當多個(gè)線(xiàn)程使用同一個(gè)連接的時(shí)候,用戶(hù)應該把寫(xiě)操作進(jìn)行序列化,以避免數據損壞。默認情況下,當調用 connect 方法的時(shí)候,
sqlite3
模塊使用了它的Connection
類(lèi)。當然,你也可以創(chuàng )建Connection
類(lèi)的子類(lèi),然后創(chuàng )建提供了 factory 參數的connect()
方法。詳情請查閱當前手冊的 SQLite 與 Python 類(lèi)型 部分。
The
sqlite3
module internally uses a statement cache to avoid SQL parsing overhead. If you want to explicitly set the number of statements that are cached for the connection, you can set the cached_statements parameter. The currently implemented default is to cache 128 statements.If uri is
True
, database is interpreted as a URI with a file path and an optional query string. The scheme part must be"file:"
. The path can be a relative or absolute file path. The query string allows us to pass parameters 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 recognized parameters, can be found in the SQLite URI documentation.
引發(fā)一個(gè) 審計事件
sqlite3.connect
,附帶參數database
。引發(fā)一個(gè) 審計事件
sqlite3.connect/handle
,附帶參數connection_handle
。在 3.4 版更改: 增加了 uri 參數。
在 3.7 版更改: database 現在可以是一個(gè) path-like object 對象了,不僅僅是字符串。
在 3.10 版更改: 增加了
sqlite3.connect/handle
審計事件。
- sqlite3.register_converter(typename, callable)?
注冊一個(gè)回調對象 callable, 用來(lái)轉換數據庫中的字節串為自定的 Python 類(lèi)型。所有類(lèi)型為 typename 的數據庫的值在轉換時(shí),都會(huì )調用這個(gè)回調對象。通過(guò)指定
connect()
函數的 detect-types 參數來(lái)設置類(lèi)型檢測的方式。注意,typename 與查詢(xún)語(yǔ)句中的類(lèi)型名進(jìn)行匹配時(shí)不區分大小寫(xiě)。
- sqlite3.register_adapter(type, callable)?
注冊一個(gè)回調對象 callable,用來(lái)轉換自定義Python類(lèi)型為一個(gè) SQLite 支持的類(lèi)型。 這個(gè)回調對象 callable 僅接受一個(gè) Python 值作為參數,而且必須返回以下某個(gè)類(lèi)型的值:int,float,str 或 bytes。
- sqlite3.complete_statement(sql)?
如果字符串 sql 包含一個(gè)或多個(gè)完整的 SQL 語(yǔ)句(以分號結束)則返回
True
。它不會(huì )驗證 SQL 語(yǔ)法是否正確,僅會(huì )驗證字符串字面上是否完整,以及是否以分號結束。它可以用來(lái)構建一個(gè) SQLite shell,下面是一個(gè)例子:
# A minimal SQLite shell for experiments import sqlite3 con = sqlite3.connect(":memory:") con.isolation_level = None cur = con.cursor() buffer = "" print("Enter your SQL commands to execute in sqlite3.") print("Enter a blank line to exit.") while True: line = input() if line == "": break buffer += line if sqlite3.complete_statement(buffer): try: buffer = buffer.strip() cur.execute(buffer) if buffer.lstrip().upper().startswith("SELECT"): print(cur.fetchall()) except sqlite3.Error as e: err_msg = str(e) err_code = e.sqlite_errorcode err_name = e.sqlite_errorname print(f"{err_name} ({err_code}): {err_msg}") 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 with flag set to
True
. Afterwards, you will get tracebacks from callbacks onsys.stderr
. UseFalse
to disable the feature again.Register an
unraisable hook handler
for an improved debug experience:>>> import sqlite3 >>> sqlite3.enable_callback_tracebacks(True) >>> cx = sqlite3.connect(":memory:") >>> cx.set_trace_callback(lambda stmt: 5/0) >>> cx.execute("select 1") Exception ignored in: <function <lambda> at 0x10b4e3ee0> Traceback (most recent call last): File "<stdin>", line 1, in <lambda> ZeroDivisionError: division by zero >>> import sys >>> sys.unraisablehook = lambda unraisable: print(unraisable) >>> cx.execute("select 1") UnraisableHookArgs(exc_type=<class 'ZeroDivisionError'>, exc_value=ZeroDivisionError('division by zero'), exc_traceback=<traceback object at 0x10b559900>, err_msg=None, object=<function <lambda> at 0x10b4e3ee0>) <sqlite3.Cursor object at 0x10b1fe840>
連接對象(Connection)?
- class sqlite3.Connection?
An SQLite database connection has the following attributes and methods:
- isolation_level?
獲取或設置當前默認的隔離級別。 表示自動(dòng)提交模式的
None
以及 "DEFERRED", "IMMEDIATE" 或 "EXCLUSIVE" 其中之一。 詳細描述請參閱 控制事務(wù)。
- cursor(factory=Cursor)?
這個(gè)方法接受一個(gè)可選參數 factory,如果要指定這個(gè)參數,它必須是一個(gè)可調用對象,而且必須返回
Cursor
類(lèi)的一個(gè)實(shí)例或者子類(lèi)。
- blobopen(table, column, row, /, *, readonly=False, name='main')?
Open a
Blob
handle to the BLOB located in table name table, column name column, and row index row of database name. When readonly isTrue
the blob is opened without write permissions. Trying to open a blob in aWITHOUT ROWID
table will raiseOperationalError
.備注
The blob size cannot be changed using the
Blob
class. Use the SQL functionzeroblob
to create a blob with a fixed size.3.11 新版功能.
- commit()?
這個(gè)方法提交當前事務(wù)。如果沒(méi)有調用這個(gè)方法,那么從上一次提交
commit()
以來(lái)所有的變化在其他數據庫連接上都是不可見(jiàn)的。如果你往數據庫里寫(xiě)了數據,但是又查詢(xún)不到,請檢查是否忘記了調用這個(gè)方法。
- close()?
關(guān)閉數據庫連接。注意,它不會(huì )自動(dòng)調用
commit()
方法。如果在關(guān)閉數據庫連接之前沒(méi)有調用commit()
,那么你的修改將會(huì )丟失!
- execute(sql[, parameters])?
Create a new
Cursor
object and callexecute()
on it with the given sql and parameters. Return the new cursor object.
- executemany(sql[, parameters])?
Create a new
Cursor
object and callexecutemany()
on it with the given sql and parameters. Return the new cursor object.
- executescript(sql_script)?
Create a new
Cursor
object and callexecutescript()
on it with the given sql_script. Return the new cursor object.
- create_function(name, num_params, func, *, deterministic=False)?
創(chuàng )建一個(gè)可以在 SQL 語(yǔ)句中使用的用戶(hù)自定義函數,函數名為 name。 num_params 為該函數所接受的形參個(gè)數(如果 num_params 為 -1,則該函數可接受任意數量的參數), func 是一個(gè) Python 可調用對象,它將作為 SQL 函數被調用。 如果 deterministic 為真值,則所創(chuàng )建的函數將被標記為 deterministic,這允許 SQLite 執行額外的優(yōu)化。 此旗標在 SQLite 3.8.3 或更高版本中受到支持,如果在舊版本中使用將引發(fā)
NotSupportedError
。此函數可返回任何 SQLite 所支持的類(lèi)型: bytes, str, int, float 和
None
。在 3.8 版更改: 增加了 deterministic 形參。
示例:
import sqlite3 import hashlib def md5sum(t): return hashlib.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)?
創(chuàng )建一個(gè)自定義的聚合函數。
參數中 aggregate_class 類(lèi)必須實(shí)現兩個(gè)方法:
step
和finalize
。step
方法接受 num_params 個(gè)參數(如果 num_params 為 -1,那么這個(gè)函數可以接受任意數量的參數);finalize
方法返回最終的聚合結果。finalize
方法可以返回任何 SQLite 支持的類(lèi)型:bytes,str,int,float 和None
。示例:
import sqlite3 class MySum: def __init__(self): self.count = 0 def step(self, value): self.count += value def finalize(self): return self.count con = 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_window_function(name, num_params, aggregate_class, /)?
Creates user-defined aggregate window function name.
aggregate_class must implement the following methods:
step
: adds a row to the current windowvalue
: returns the current value of the aggregateinverse
: removes a row from the current windowfinalize
: returns the final value of the aggregate
step
andvalue
accept num_params number of parameters, unless num_params is-1
, in which case they may take any number of arguments.finalize
andvalue
can return any of the types supported by SQLite:bytes
,str
,int
,float
, andNone
. Callcreate_window_function()
with aggregate_class set toNone
to clear window function name.Aggregate window functions are supported by SQLite 3.25.0 and higher.
NotSupportedError
will be raised if used with older versions.3.11 新版功能.
示例:
# Example taken from https://www.sqlite.org/windowfunctions.html#udfwinfunc import sqlite3 class WindowSumInt: def __init__(self): self.count = 0 def step(self, value): """Adds a row to the current window.""" self.count += value def value(self): """Returns the current value of the aggregate.""" return self.count def inverse(self, value): """Removes a row from the current window.""" self.count -= value def finalize(self): """Returns the final value of the aggregate. Any clean-up actions should be placed here. """ return self.count con = sqlite3.connect(":memory:") cur = con.execute("create table test(x, y)") values = [ ("a", 4), ("b", 5), ("c", 3), ("d", 8), ("e", 1), ] cur.executemany("insert into test values(?, ?)", values) con.create_window_function("sumint", 1, WindowSumInt) cur.execute(""" select x, sumint(y) over ( order by x rows between 1 preceding and 1 following ) as sum_y from test order by x """) print(cur.fetchall())
- create_collation(name, callable)?
Create a collation named name using the collating function callable. callable is passed two
string
arguments, and it should return aninteger
:1
if the first is ordered higher than the second-1
if the first is ordered lower than the second0
if they are ordered equal
The following example shows a reverse sorting collation:
import sqlite3 def collate_reverse(string1, string2): if string1 == string2: return 0 elif string1 < string2: return 1 else: return -1 con = 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") for row in cur: print(row) con.close()
Remove a collation function by setting callable to
None
.在 3.11 版更改: The collation name can contain any Unicode character. Earlier, only ASCII characters were allowed.
- interrupt()?
可以從不同的線(xiàn)程調用這個(gè)方法來(lái)終止所有查詢(xún)操作,這些查詢(xún)操作可能正在連接上執行。此方法調用之后, 查詢(xún)將會(huì )終止,而且查詢(xún)的調用者會(huì )獲得一個(gè)異常。
- set_authorizer(authorizer_callback)?
此方法注冊一個(gè)授權回調對象。每次在訪(fǎng)問(wèn)數據庫中某個(gè)表的某一列的時(shí)候,這個(gè)回調對象將會(huì )被調用。如果要允許訪(fǎng)問(wèn),則返回
SQLITE_OK
,如果要終止整個(gè) SQL 語(yǔ)句,則返回SQLITE_DENY
,如果這一列需要當做 NULL 值處理,則返回SQLITE_IGNORE
。這些常量可以在sqlite3
模塊中找到。回調的第一個(gè)參數表示要授權的操作類(lèi)型。 第二個(gè)和第三個(gè)參數將是參數或
None
,具體取決于第一個(gè)參數的值。 第 4 個(gè)參數是數據庫的名稱(chēng)(“main”,“temp”等),如果需要的話(huà)。 第 5 個(gè)參數是負責訪(fǎng)問(wèn)嘗試的最內層觸發(fā)器或視圖的名稱(chēng),或者如果此訪(fǎng)問(wèn)嘗試直接來(lái)自輸入 SQL 代碼,則為None
。請參閱 SQLite 文檔,了解第一個(gè)參數的可能值以及第二個(gè)和第三個(gè)參數的含義,具體取決于第一個(gè)參數。 所有必需的常量都可以在
sqlite3
模塊中找到。Passing
None
as authorizer_callback will disable the authorizer.在 3.11 版更改: Added support for disabling the authorizer using
None
.
- set_progress_handler(handler, n)?
此例程注冊回調。 對SQLite虛擬機的每個(gè)多指令調用回調。 如果要在長(cháng)時(shí)間運行的操作期間從SQLite調用(例如更新用戶(hù)界面),這非常有用。
如果要清除以前安裝的任何進(jìn)度處理程序,調用該方法時(shí)請將 handler 參數設置為
None
。從處理函數返回非零值將終止當前正在執行的查詢(xún)并導致它引發(fā)
OperationalError
異常。
- set_trace_callback(trace_callback)?
為每個(gè) SQLite 后端實(shí)際執行的 SQL 語(yǔ)句注冊要調用的 trace_callback。
The only argument passed to the callback is the statement (as
str
) that is being executed. The return value of the callback is ignored. Note that the backend does not only run statements passed to theCursor.execute()
methods. Other sources include the transaction management of the sqlite3 module and the execution of triggers defined in the current database.將傳入的 trace_callback 設為
None
將禁用跟蹤回調。備注
Exceptions raised in the trace callback are not propagated. As a development and debugging aid, use
enable_callback_tracebacks()
to enable printing tracebacks from exceptions raised in the trace callback.3.3 新版功能.
- enable_load_extension(enabled)?
此例程允許/禁止SQLite引擎從共享庫加載SQLite擴展。 SQLite擴展可以定義新功能,聚合或全新的虛擬表實(shí)現。 一個(gè)眾所周知的擴展是與SQLite一起分發(fā)的全文搜索擴展。
默認情況下禁用可加載擴展。 見(jiàn) 1.
引發(fā)一個(gè) 審計事件
sqlite3.enable_load_extension
,附帶參數connection
,enabled
。3.2 新版功能.
在 3.10 版更改: 增加了
sqlite3.enable_load_extension
審計事件。import sqlite3 con = sqlite3.connect(":memory:") # enable extension loading con.enable_load_extension(True) # Load the fulltext search extension con.execute("select load_extension('./fts3.so')") # alternatively you can load the extension using an API call: # con.load_extension("./fts3.so") # disable extension loading again con.enable_load_extension(False) # example from SQLite wiki con.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'); """) for row in con.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 to enable extension loading with
enable_load_extension()
before you can use this routine.默認情況下禁用可加載擴展。 見(jiàn) 1.
引發(fā)一個(gè) 審計事件
sqlite3.load_extension
,附帶參數connection
,path
。3.2 新版功能.
在 3.10 版更改: 增加了
sqlite3.load_extension
審計事件。
- row_factory?
您可以將此屬性更改為可接受游標和原始行作為元組的可調用對象,并將返回實(shí)際結果行。 這樣,您可以實(shí)現更高級的返回結果的方法,例如返回一個(gè)可以按名稱(chēng)訪(fǎng)問(wèn)列的對象。
示例:
import sqlite3 def dict_factory(cursor, row): d = {} for idx, col in enumerate(cursor.description): d[col[0]] = row[idx] return d con = sqlite3.connect(":memory:") con.row_factory = dict_factory cur = con.cursor() cur.execute("select 1 as a") print(cur.fetchone()["a"]) con.close()
如果返回一個(gè)元組是不夠的,并且你想要對列進(jìn)行基于名稱(chēng)的訪(fǎng)問(wèn),你應該考慮將
row_factory
設置為高度優(yōu)化的sqlite3.Row
類(lèi)型。Row
提供基于索引和不區分大小寫(xiě)的基于名稱(chēng)的訪(fǎng)問(wèn),幾乎沒(méi)有內存開(kāi)銷(xiāo)。 它可能比您自己的基于字典的自定義方法甚至基于 db_row 的解決方案更好。
- text_factory?
Using this attribute you can control what objects are returned for the
TEXT
data type. By default, this attribute is set tostr
and thesqlite3
module will returnstr
objects forTEXT
. If you want to returnbytes
instead, you can set it tobytes
.您還可以將其設置為接受單個(gè) bytestring 參數的任何其他可調用對象,并返回結果對象。
請參閱以下示例代碼以進(jìn)行說(shuō)明:
import sqlite3 con = sqlite3.connect(":memory:") cur = con.cursor() AUSTRIA = "?sterreich" # by default, rows are returned as str cur.execute("select ?", (AUSTRIA,)) row = cur.fetchone() assert row[0] == AUSTRIA # but we can make sqlite3 always return bytestrings ... con.text_factory = bytes cur.execute("select ?", (AUSTRIA,)) row = cur.fetchone() assert type(row[0]) is bytes # the bytestrings will be encoded in UTF-8, unless you stored garbage in the # database ... assert row[0] == AUSTRIA.encode("utf-8") # we can also implement a custom text_factory ... # here we implement one that appends "foo" to all strings con.text_factory = lambda x: x.decode("utf-8") + "foo" cur.execute("select ?", ("bar",)) row = cur.fetchone() assert row[0] == "barfoo" con.close()
- total_changes?
返回自打開(kāi)數據庫連接以來(lái)已修改,插入或刪除的數據庫行的總數。
- iterdump()?
返回以SQL文本格式轉儲數據庫的迭代器。 保存內存數據庫以便以后恢復時(shí)很有用。 此函數提供與 sqlite3 shell 中的 .dump 命令相同的功能。
示例:
# Convert file existing_db.db to SQL dump file dump.sql import sqlite3 con = sqlite3.connect('existing_db.db') with open('dump.sql', 'w') as f: for line in con.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 accessed by other clients, or concurrently by the same connection. The copy will be written into the mandatory argument target, that must be another
Connection
instance.默認情況下,或者當 pages 為
0
或負整數時(shí),整個(gè)數據庫將在一個(gè)步驟中復制;否則該方法一次循環(huán)復制 pages 規定數量的頁(yè)面。如果指定了 progress,則它必須為
None
或一個(gè)將在每次迭代時(shí)附帶三個(gè)整數參數執行的可調用對象,這三個(gè)參數分別是前一次迭代的狀態(tài) status,將要拷貝的剩余頁(yè)數 remaining 以及總頁(yè)數 total。name 參數指定將被拷貝的數據庫名稱(chēng):它必須是一個(gè)字符串,其內容為表示主數據庫的默認值
"main"
,表示臨時(shí)數據庫的"temp"
或是在ATTACH DATABASE
語(yǔ)句的AS
關(guān)鍵字之后指定表示附加數據庫的名稱(chēng)。sleep 參數指定在備份剩余頁(yè)的連續嘗試之間要休眠的秒數,可以指定為一個(gè)整數或一個(gè)浮點(diǎn)數值。
示例一,將現有數據庫復制到另一個(gè)數據庫中:
import sqlite3 def progress(status, remaining, total): print(f'Copied {total-remaining} of {total} pages...') con = sqlite3.connect('existing_db.db') bck = sqlite3.connect('backup.db') with bck: con.backup(bck, pages=1, progress=progress) bck.close() con.close()
示例二,將現有數據庫復制到臨時(shí)副本中:
import sqlite3 source = sqlite3.connect('existing_db.db') dest = sqlite3.connect(':memory:') source.backup(dest)
3.7 新版功能.
- getlimit(category, /)?
Get a connection run-time limit. category is the limit category to be queried.
Example, query the maximum length of an SQL statement:
import sqlite3 con = sqlite3.connect(":memory:") lim = con.getlimit(sqlite3.SQLITE_LIMIT_SQL_LENGTH) print(f"SQLITE_LIMIT_SQL_LENGTH={lim}")
3.11 新版功能.
- setlimit(category, limit, /)?
Set a connection run-time limit. category is the limit category to be set. limit is the new limit. If the new limit is a negative number, the limit is unchanged.
Attempts to increase a limit above its hard upper bound are silently truncated to the hard upper bound. Regardless of whether or not the limit was changed, the prior value of the limit is returned.
Example, limit the number of attached databases to 1:
import sqlite3 con = sqlite3.connect(":memory:") con.setlimit(sqlite3.SQLITE_LIMIT_ATTACHED, 1)
3.11 新版功能.
- serialize(*, name='main')?
This method serializes a database into a
bytes
object. For an ordinary on-disk database file, the serialization is just a copy of the disk file. For an in-memory database or a "temp" database, the serialization is the same sequence of bytes which would be written to disk if that database were backed up to disk.name is the database to be serialized, and defaults to the main database.
備注
This method is only available if the underlying SQLite library has the serialize API.
3.11 新版功能.
- deserialize(data, /, *, name='main')?
This method causes the database connection to disconnect from database name, and reopen name as an in-memory database based on the serialization contained in data. Deserialization will raise
OperationalError
if the database connection is currently involved in a read transaction or a backup operation.DataError
will be raised iflen(data)
is larger than2**63 - 1
, andDatabaseError
will be raised if data does not contain a valid SQLite database.備注
This method is only available if the underlying SQLite library has the deserialize API.
3.11 新版功能.
Cursor 對象?
- class sqlite3.Cursor?
Cursor
游標實(shí)例具有以下屬性和方法。- execute(sql[, parameters])?
執行一條 SQL 語(yǔ)句。 可以使用 占位符 將值綁定到語(yǔ)句中。
execute()
將只執行一條單獨的 SQL 語(yǔ)句。 如果你嘗試用它執行超過(guò)一條語(yǔ)句,將會(huì )引發(fā)Warning
。 如果你想要用一次調用執行多條 SQL 語(yǔ)句請使用executescript()
。
- executemany(sql, seq_of_parameters)?
執行一條 帶形參的 SQL 命令,使用所有形參序列或在序列 seq_of_parameters 中找到的映射。
sqlite3
模塊還允許使用 iterator 代替序列來(lái)產(chǎn)生形參。import sqlite3 class IterChars: def __init__(self): self.count = ord('a') def __iter__(self): return self def __next__(self): if self.count > ord('z'): raise StopIteration self.count += 1 return (chr(self.count - 1),) # this is a 1-tuple con = 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()
這是一個(gè)使用生成器 generator 的簡(jiǎn)短示例:
import sqlite3 import string def char_generator(): for c in string.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)?
這是用于一次性執行多條 SQL 語(yǔ)句的非標準便捷方法。 它會(huì )首先發(fā)出一條
COMMIT
語(yǔ)句,然后執行通過(guò)參數獲得的 SQL 腳本。 此方法會(huì )忽略isolation_level
;任何事件控制都必須被添加到 sql_script。sql_script 可以是一個(gè)
str
類(lèi)的實(shí)例。示例:
import sqlite3 con = 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()
- fetchmany(size=cursor.arraysize)?
獲取下一個(gè)多行查詢(xún)結果集,返回一個(gè)列表。 當沒(méi)有更多可用行時(shí)將返回一個(gè)空列表。
每次調用獲取的行數由 size 形參指定。 如果沒(méi)有給出該形參,則由 cursor 的 arraysize 決定要獲取的行數。 此方法將基于 size 形參值嘗試獲取指定數量的行。 如果獲取不到指定的行數,則可能返回較少的行。
請注意 size 形參會(huì )涉及到性能方面的考慮。為了獲得優(yōu)化的性能,通常最好是使用 arraysize 屬性。 如果使用 size 形參,則最好在從一個(gè)
fetchmany()
調用到下一個(gè)調用之間保持相同的值。
- fetchall()?
獲取一個(gè)查詢(xún)結果的所有(剩余)行,返回一個(gè)列表。 請注意 cursor 的 arraysize 屬性會(huì )影響此操作的執行效率。 當沒(méi)有可用行時(shí)將返回一個(gè)空列表。
- close()?
立即關(guān)閉 cursor(而不是在當
__del__
被調用的時(shí)候)。從這一時(shí)刻起該 cursor 將不再可用,如果再?lài)L試用該 cursor 執行任何操作將引發(fā)
ProgrammingError
異常。
- rowcount?
雖然
sqlite3
模塊的Cursor
類(lèi)實(shí)現了此屬性,但數據庫引擎本身對于確定 "受影響行"/"已選擇行" 的支持并不完善。對于
executemany()
語(yǔ)句,修改行數會(huì )被匯總至rowcount
。根據 Python DB API 規格描述的要求,
rowcount
屬性 "當未在 cursor 上執行executeXX()
或者上一次操作的 rowcount 不是由接口確定時(shí)為 -1"。 這包括SELECT
語(yǔ)句,因為我們無(wú)法確定一次查詢(xún)將產(chǎn)生的行計數,而要等獲取了所有行時(shí)才會(huì )知道。
- lastrowid?
This read-only attribute provides the row id of the last inserted row. It is only updated after successful
INSERT
orREPLACE
statements using theexecute()
method. For other statements, afterexecutemany()
orexecutescript()
, or if the insertion failed, the value oflastrowid
is left unchanged. The initial value oflastrowid
isNone
.備注
Inserts into
WITHOUT ROWID
tables are not recorded.在 3.6 版更改: 增加了
REPLACE
語(yǔ)句的支持。
- arraysize?
用于控制
fetchmany()
返回行數的可讀取/寫(xiě)入屬性。 該屬性的默認值為 1,表示每次調用將獲取單獨一行。
- description?
這個(gè)只讀屬性將提供上一次查詢(xún)的列名稱(chēng)。 為了與 Python DB API 保持兼容,它會(huì )為每個(gè)列返回一個(gè) 7 元組,每個(gè)元組的最后六個(gè)條目均為
None
。對于沒(méi)有任何匹配行的
SELECT
語(yǔ)句同樣會(huì )設置該屬性。
- connection?
這個(gè)只讀屬性將提供
Cursor
對象所使用的 SQLite 數據庫Connection
。 通過(guò)調用con.cursor()
創(chuàng )建的Cursor
對象所包含的connection
屬性將指向 con:>>> con = sqlite3.connect(":memory:") >>> cur = con.cursor() >>> cur.connection == con True
行對象?
- class sqlite3.Row?
一個(gè)
Row
實(shí)例,該實(shí)例將作為用于Connection
對象的高度優(yōu)化的row_factory
。 它的大部分行為都會(huì )模仿元組的特性。它支持使用列名稱(chēng)的映射訪(fǎng)問(wèn)以及索引、迭代、文本表示、相等檢測和
len()
等操作。如果兩個(gè)
Row
對象具有完全相同的列并且其成員均相等,則它們的比較結果為相等。- keys()?
此方法會(huì )在一次查詢(xún)之后立即返回一個(gè)列名稱(chēng)的列表,它是
Cursor.description
中每個(gè)元組的第一個(gè)成員。
在 3.5 版更改: 添加了對切片操作的支持。
讓我們假設我們如上面的例子所示初始化一個(gè)表:
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()
現在我們將 Row
插入:
>>> 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
>>> for member in r:
... print(member)
...
2006-01-05
BUY
RHAT
100.0
35.14
Blob Objects?
3.11 新版功能.
- class sqlite3.Blob?
A
Blob
instance is a file-like object that can read and write data in an SQLite BLOB. Calllen(blob)
to get the size (number of bytes) of the blob. Use indices and slices for direct access to the blob data.Use the
Blob
as a context manager to ensure that the blob handle is closed after use.import sqlite3 con = sqlite3.connect(":memory:") con.execute("create table test(blob_col blob)") con.execute("insert into test(blob_col) values (zeroblob(13))") # Write to our blob, using two write operations: with con.blobopen("test", "blob_col", 1) as blob: blob.write(b"hello, ") blob.write(b"world.") # Modify the first and last bytes of our blob blob[0] = ord("H") blob[-1] = ord("!") # Read the contents of our blob with con.blobopen("test", "blob_col", 1) as blob: greeting = blob.read() print(greeting) # outputs "b'Hello, world!'"
- close()?
Close the blob.
The blob will be unusable from this point onward. An
Error
(or subclass) exception will be raised if any further operation is attempted with the blob.
- read(length=- 1, /)?
Read length bytes of data from the blob at the current offset position. If the end of the blob is reached, the data up to EOF will be returned. When length is not specified, or is negative,
read()
will read until the end of the blob.
- write(data, /)?
Write data to the blob at the current offset. This function cannot change the blob length. Writing beyond the end of the blob will raise
ValueError
.
- tell()?
Return the current access position of the blob.
- seek(offset, origin=os.SEEK_SET, /)?
Set the current access position of the blob to offset. The origin argument defaults to
os.SEEK_SET
(absolute blob positioning). Other values for origin areos.SEEK_CUR
(seek relative to the current position) andos.SEEK_END
(seek relative to the blob’s end).
異常?
- exception sqlite3.Error?
此模塊中其他異常的基類(lèi)。 它是
Exception
的一個(gè)子類(lèi)。- sqlite_errorcode?
The numeric error code from the SQLite API
3.11 新版功能.
- sqlite_errorname?
The symbolic name of the numeric error code from the SQLite API
3.11 新版功能.
- exception sqlite3.DatabaseError?
針對數據庫相關(guān)錯誤引發(fā)的異常。
- exception sqlite3.IntegrityError?
當數據庫的關(guān)系一致性受到影響時(shí)引發(fā)的異常。 例如外鍵檢查失敗等。 它是
DatabaseError
的子類(lèi)。
- exception sqlite3.ProgrammingError?
編程錯誤引發(fā)的異常,例如表未找到或已存在,SQL 語(yǔ)句存在語(yǔ)法錯誤,指定的形參數量錯誤等。 它是
DatabaseError
的子類(lèi)。
- exception sqlite3.OperationalError?
與數據庫操作相關(guān)而不一定能受程序員掌控的錯誤引發(fā)的異常,例如發(fā)生非預期的連接中斷,數據源名稱(chēng)未找到,事務(wù)無(wú)法被執行等。 它是
DatabaseError
的子類(lèi)。
- exception sqlite3.NotSupportedError?
在使用了某個(gè)數據庫不支持的方法或數據庫 API 時(shí)引發(fā)的異常,例如在一個(gè)不支持事務(wù)或禁用了事務(wù)的連接上調用
rollback()
方法等。 它是DatabaseError
的子類(lèi)。
SQLite 與 Python 類(lèi)型?
概述?
SQLite 原生支持如下的類(lèi)型: NULL
,INTEGER
,REAL
,TEXT
,BLOB
。
因此可以將以下Python類(lèi)型發(fā)送到SQLite而不會(huì )出現任何問(wèn)題:
Python 類(lèi)型 |
SQLite 類(lèi)型 |
---|---|
|
|
|
|
|
|
|
|
|
這是SQLite類(lèi)型默認轉換為Python類(lèi)型的方式:
SQLite 類(lèi)型 |
Python 類(lèi)型 |
---|---|
|
|
|
|
|
|
|
取決于 |
|
The type system of the sqlite3
module is extensible in two ways: you can
store additional Python types in an SQLite database via object adaptation, and
you can let the sqlite3
module convert SQLite types to different Python
types via converters.
使用適配器將額外的 Python 類(lèi)型保存在 SQLite 數據庫中。?
如上文所述,SQLite 只包含對有限類(lèi)型集的原生支持。 要讓 SQLite 能使用其他 Python 類(lèi)型,你必須將它們 適配 至 sqlite3 模塊所支持的 SQLite 類(lèi)型中的一種:NoneType, int, float, str, bytes。
有兩種方式能讓 sqlite3
模塊將某個(gè)定制的 Python 類(lèi)型適配為受支持的類(lèi)型。
讓對象自行適配?
如果類(lèi)是你自己編寫(xiě)的,這將是一個(gè)很好的方式。 假設你有這樣一個(gè)類(lèi):
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
現在你可將這種點(diǎn)對象保存在一個(gè) SQLite 列中。 首先你必須選擇一種受支持的類(lèi)型用來(lái)表示點(diǎn)對象。 讓我們就用 str 并使用一個(gè)分號來(lái)分隔坐標值。 然后你需要給你的類(lèi)加一個(gè)方法 __conform__(self, protocol)
,它必須返回轉換后的值。 形參 protocol 將為 PrepareProtocol
。
import sqlite3
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __conform__(self, protocol):
if protocol is sqlite3.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()
注冊可調用的適配器?
另一種可能的做法是創(chuàng )建一個(gè)將該類(lèi)型轉換為字符串表示的函數并使用 register_adapter()
注冊該函數。
import sqlite3
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def adapt_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()
sqlite3
模塊有兩個(gè)適配器可用于 Python 的內置 datetime.date
和 datetime.datetime
類(lèi)型。 現在假設我們想要存儲 datetime.datetime
對象,但不是表示為 ISO 格式,而是表示為 Unix 時(shí)間戳。
import sqlite3
import datetime
import time
def adapt_datetime(ts):
return time.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()
將SQLite 值轉換為自定義Python 類(lèi)型?
編寫(xiě)適配器讓你可以將定制的 Python 類(lèi)型發(fā)送給 SQLite。 但要令它真正有用,我們需要實(shí)現從 Python 到 SQLite 再回到 Python 的雙向轉換。
輸入轉換器。
讓我們回到 Point
類(lèi)。 我們以字符串形式在 SQLite 中存儲了 x 和 y 坐標值。
首先,我們將定義一個(gè)轉換器函數,它接受這樣的字符串作為形參并根據該參數構造一個(gè) Point
對象。
備注
轉換器函數在調用時(shí) 總是 會(huì )附帶一個(gè) bytes
對象,無(wú)論你將何種數據類(lèi)型的值發(fā)給 SQLite。
def convert_point(s):
x, y = map(float, s.split(b";"))
return Point(x, y)
現在你需要讓 sqlite3
模塊知道你從數據庫中選取的其實(shí)是一個(gè)點(diǎn)對象。 有兩種方式都可以做到這件事:
隱式的聲明類(lèi)型
顯式的通過(guò)列名
這兩種方式會(huì )在 模塊函數和常量 一節中描述,相應條目為 PARSE_DECLTYPES
和 PARSE_COLNAMES
常量。
下面的示例說(shuō)明了這兩種方法。
import sqlite3
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return "(%f;%f)" % (self.x, self.y)
def adapt_point(point):
return ("%f;%f" % (point.x, point.y)).encode('ascii')
def convert_point(s):
x, y = list(map(float, s.split(b";")))
return Point(x, y)
# Register the adapter
sqlite3.register_adapter(Point, adapt_point)
# Register the converter
sqlite3.register_converter("point", convert_point)
p = Point(4.0, -3.2)
#########################
# 1) Using declared types
con = 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 names
con = 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()
默認適配器和轉換器?
對于 datetime 模塊中的 date 和 datetime 類(lèi)型已提供了默認的適配器。 它們將會(huì )以 ISO 日期/ISO 時(shí)間戳的形式發(fā)給 SQLite。
默認轉換器使用的注冊名稱(chēng)是針對 datetime.date
的 "date" 和針對 datetime.datetime
的 "timestamp"。
通過(guò)這種方式,你可以在大多數情況下使用 Python 的 date/timestamp 對象而無(wú)須任何額外處理。 適配器的格式還與實(shí)驗性的 SQLite date/time 函數兼容。
下面的示例演示了這一點(diǎn)。
import sqlite3
import datetime
con = 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()
如果存儲在 SQLite 中的時(shí)間戳的小數位多于 6 個(gè)數字,則時(shí)間戳轉換器會(huì )將該值截斷至微秒精度。
備注
The default "timestamp" converter ignores UTC offsets in the database and
always returns a naive datetime.datetime
object. To preserve UTC
offsets in timestamps, either leave converters disabled, or register an
offset-aware converter with register_converter()
.
控制事務(wù)?
底層的 sqlite3
庫默認會(huì )以 autocommit
模式運行,但 Python 的 sqlite3
模塊默認則不使用此模式。
autocommit
模式意味著(zhù)修改數據庫的操作會(huì )立即生效。 BEGIN
或 SAVEPOINT
語(yǔ)句會(huì )禁用 autocommit
模式,而用于結束外層事務(wù)的 COMMIT
, ROLLBACK
或 RELEASE
則會(huì )恢復 autocommit
模式。
Python 的 sqlite3
模塊默認會(huì )在數據修改語(yǔ)言 (DML) 類(lèi)語(yǔ)句 (即 INSERT
/UPDATE
/DELETE
/REPLACE
) 之前隱式地執行一條 BEGIN
語(yǔ)句。
你可以控制 sqlite3
隱式執行的 BEGIN
語(yǔ)句的種類(lèi),具體做法是通過(guò)將 isolation_level 形參傳給 connect()
調用,或者通過(guò)指定連接的 isolation_level
屬性。 如果你沒(méi)有指定 isolation_level,將使用基本的 BEGIN
,它等價(jià)于指定 DEFERRED
。 其他可能的值為 IMMEDIATE
和 EXCLUSIVE
。
你可以禁用 sqlite3
模塊的隱式事務(wù)管理,具體做法是將 isolation_level
設為 None
。 這將使得下層的 sqlite3
庫采用 autocommit
模式。 隨后你可以通過(guò)在代碼中顯式地使用 BEGIN
, ROLLBACK
, SAVEPOINT
和 RELEASE
語(yǔ)句來(lái)完全控制事務(wù)狀態(tài)。
請注意 executescript()
會(huì )忽略 isolation_level
;任何事務(wù)控制必要要顯式地添加。
在 3.6 版更改: 以前 sqlite3
會(huì )在 DDL 語(yǔ)句之前隱式地提交未完成事務(wù)。 現在則不會(huì )再這樣做。
有效使用 sqlite3
?
使用快捷方式?
使用 Connection
對象的非標準 execute()
, executemany()
和 executescript()
方法,可以更簡(jiǎn)潔地編寫(xiě)代碼,因為不必顯式創(chuàng )建(通常是多余的) Cursor
對象。相反, Cursor
對象是隱式創(chuàng )建的,這些快捷方法返回游標對象。這樣,只需對 Connection
對象調用一次,就能直接執行 SELECT
語(yǔ)句并遍歷對象。
import sqlite3
langs = [
("C++", 1985),
("Objective-C", 1984),
]
con = sqlite3.connect(":memory:")
# Create the table
con.execute("create table lang(name, first_appeared)")
# Fill the table
con.executemany("insert into lang(name, first_appeared) values (?, ?)", langs)
# Print the table contents
for row in con.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 manually
con.close()
通過(guò)名稱(chēng)而不是索引訪(fǎng)問(wèn)索引?
sqlite3
模塊的一個(gè)有用功能是內置的 sqlite3.Row
類(lèi),它被設計用作行對象的工廠(chǎng)。
該類(lèi)的行裝飾器可以用索引(如元組)和不區分大小寫(xiě)的名稱(chēng)訪(fǎng)問(wèn):
import sqlite3
con = sqlite3.connect(":memory:")
con.row_factory = sqlite3.Row
cur = con.cursor()
cur.execute("select 'John' as name, 42 as age")
for row in cur:
assert row[0] == row["name"]
assert row["name"] == row["nAmE"]
assert row[1] == row["age"]
assert row[1] == row["AgE"]
con.close()
使用連接作為上下文管理器?
連接對象可以用來(lái)作為上下文管理器,它可以自動(dòng)提交或者回滾事務(wù)。如果出現異常,事務(wù)會(huì )被回滾;否則,事務(wù)會(huì )被提交。
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("create table lang (id integer primary key, name varchar unique)")
# Successful, con.commit() is called automatically afterwards
with con:
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 caught
try:
with con:
con.execute("insert into lang(name) values (?)", ("Python",))
except sqlite3.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 manually
con.close()
備注
- 1(1,2)
The sqlite3 module is not built with loadable extension support by default, because some platforms (notably macOS) have SQLite libraries which are compiled without this feature. To get loadable extension support, you must pass the
--enable-loadable-sqlite-extensions
option to configure.