嗨,使用线程写入数据库的最佳方法是什么?在编写数据时是否只需要一个简单的锁定,或者除了使用线程之外还有更好的方法吗?
我想做这样的事情:
from threading import Thread
from Queue import Queue
import sqlite3
class MyThread(Thread):
def __init__(self, val,val2):
''' Constructor. '''
Thread.__init__(self)
self.val = val
self.val2 = val2
def run(self):
db = sqlite3.connect('C:\myDB.db')
cursor = db.cursor()
commandText='INSERT INTO Cars(name,carId) values({0} , {1})'.format(self.val, self.val2)
cursor.execute(commandText)
db.commit()
class MyThread2(Thread):
def __init__(self, val,val2):
''' Constructor. '''
Thread.__init__(self)
self.val = val
self.val2 = val2
def run(self):
db = sqlite3.connect('C:\myDB.db')
cursor = db.cursor()
commandText='INSERT INTO Person(name,personId) values({0} , {1})'.format(self.val, self.val2)
cursor.execute(commandText)
db.commit()
if __name__=='__main__':
db='C:\CMDB\CM.db'
myThreadOb1 = MyThread("car1",8)
myThreadOb1.setName('Thread 1')
myThreadOb2 = MyThread2("mark",9)
myThreadOb2.setName('Thread 2')
# Start running the threads!
myThreadOb1.start()
myThreadOb2.start()