数据库锁定错误最可能的原因是您必须执行
conn.commit()
数据库操作完成后。否则, 数据库将被写锁定并保持不变。等待写入的其余线程将在一段时间后断开连接(默认值为5秒, 有关详细信息, 请参见
http://docs.python.org/2/library/sqlite3.html#sqlite3.connect
关于它)。
正确且同时插入的示例如下:
import threading, sqlite3
class InsertionThread(threading.Thread):
def __init__(self, number):
super(InsertionThread, self).__init__()
self.number = number
def run(self):
conn = sqlite3.connect('yourdb.db', timeout=5)
conn.execute('CREATE TABLE IF NOT EXISTS threadcount (threadnum, count);')
conn.commit()
for i in range(1000):
conn.execute("INSERT INTO threadcount VALUES (?, ?);", (self.number, i))
conn.commit()
# create as many of these as you wish
# but be careful to set the timeout value appropriately: thread switching in
# python takes some time
for i in range(2):
t = InsertionThread(i)
t.start()
如果您喜欢SQLite或拥有可用于SQLite数据库的其他工具, 或者想用SQLitedb文件替换CSV文件, 或者需要执行诸如跨平台IPC之类的罕见任务, 那么SQLite是一个很好的工具, 非常适合这个目标。如果对您不起作用, 请不要强行使用其他解决方案!