class sqlite3.Connection
本类定义了SQLite数据库连接,它的属性和方法如下:
isolation_level
隔离的级别。None表示自动模式,可以选择“DEFERRED”、“IMMEDIATE”或者“EXCLUSIVE”等级。
in_transaction
返回是否还在事务当中,如果是返回True,否则返回False。本属性只读。
cursor([cursorClass])
设置用户自定义的cursor类,此类需要派生于sqlite3.Cursor。
commit()
提交当前数据库操作的事务。如果忘记调用此函数,从别的连接查看数据库,就不会看到任何未提交事务的数据。
rollback()
从最一次commit()的事务进行回滚,即是放弃当前进行的修改。
close()
关闭当前数据库连接。如果当前连接执行的事务没有提交,所有变化将会丢失,即是调用本函数不会自动提交事务的操作。
execute(sql[, parameters])
本函数是一个非标准的快捷执行SQL语句的函数。它会在执行SQL语句之前先自动创建一个临时cursor对象,调用cursor对象的函数execute()。
executemany(sql[, parameters])
本函数是一个非标准的快捷执行SQL语句的函数。它会在执行SQL语句之前先自动创建一个临时cursor对象,调用cursor对象的函数executemany()。
executescript(sql_script)
本函数是一个非标准的快捷执行SQL语句的函数。它会在执行SQL语句之前先自动创建一个临时cursor对象,调用cursor对象的函数executescript()。
create_function(name, num_params, func)
创建一个用户自定义函数,可以给后面的SQL语句来访问。参数name是函数的名称;参数num_params是函数接受的参数;参数func是被SQL语句可以调用的函数。函数可以返回SQLite数据库支持的类型: bytes, str, int, float 和 None.
例子:
#python 3.4
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])
结果输出如下:
acbd18db4cc2f85cedef654fccc4a4d8
create_aggregate(name, num_params, aggregate_class)
创建一个用户自定义聚合类函数。
例子:
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])
create_collation(name, callable)
创建一个数据比较函数。
例子:
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()
interrupt()
中断别的线程执行查询的操作,并让查询线程收到异常。
set_authorizer(authorizer_callback)
注册一个回调函数,当访问数据库表的一列时就会调用注册的函数。如果允许访问,就返回SQLITE_OK;如果不允许访问返回 SQLITE_DENY;如果是一个空值就返回SQLITE_IGNORE。
set_progress_handler(handler, n)
注册一个给SQLite进行回调运行的函数,当SQLite数据库的虚拟机运行几条指令之后就调用注册函数一次,以便给GUI界面进行更新。
set_trace_callback(trace_callback)
注册一个当SQL语句执行之后调用的函数。
enable_load_extension(enabled)
设置是否允许SQLite加载SQLite扩展库。
例子:
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 laoding 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)
load_extension(path)
从指定路径里加载SQLite扩展共享库。
row_factory
此属性可以用来修改返回行的结果集。
例子:
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"])
text_factory
用此属性来控制从TEXT字段返回可以得到什么类型对象。比如默认是返回UNICODE对象类型,可以通过此属性返回bytes类型。
例子:
import sqlite3
con = sqlite3.connect(":memory:")
cur = con.cursor()
AUSTRIA = "\xd6sterreich"
# by default, rows are returned as Unicode
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"
total_changes
返回连接器创建之后,有多少行数据被修改、插入或删除。
iterdump
转换数据库为SQL文本方式,然后通过本迭代器进行访问输出。
例子:
import sqlite3, os
con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
for line in con.iterdump():
f.write('%s\n' % line)
蔡军生 QQ:9073204 深圳