Python标准库中有sqlite3模块,可见对此数据库的认可。不过,此模块在使用时也有限制,同一个数据库连接,不能在不同线程中共享。
import threading
import sqlite3
sqlite_mutex = threading.Lock()
db = sqlite3.connect('tdb2')
def initdb():
try:
db.executescript("""
create table stocks(id integer primary key, name text);
""")
except Exception as e:
print(repr(e))
def insertdb(name):
with sqlite_mutex:
try:
for i in range(100):
db.execute('insert into stocks values (%d,%s)'%(i,name))
except Exception as e:
print(repr(e))
initdb()
ths = []
for i in range(10):
th = threading.Thread(target=insertdb, args=(str(i),))
ths.append(th)
for i in range(10):
ths[i].start()
for i in range(10):
ths[i].