Python多线程sqlite3插入

时间:2017-06-08 23:06:14

标签: python multithreading sqlite

我想制作一个包含多个线程的程序。在每个线程中应该是一个数据库INSERT。

修改

但是现在我在一段时间后得到了同样的错误

我的代码:

import threading, sqlite3



class myThread(threading.Thread):


   def __init__(self, pn, icm):
       threading.Thread.__init__(self)
       self.pn = pn
       self.icm = icm


   def run(self):

       con = sqlite3.connect("DB.db", check_same_thread=False)
       cursor = con.cursor()
       cursor.execute("CREATE TABLE IF NOT EXISTS test(pn VARCHAR(100), icm VARCHAR(100))")
       cursor.execute("INSERT INTO test VALUES('"+self.pn+"', '"+self.icm+"')")
       con.commit()
       con.close()


for i in range(0, 300):
   myThread("ABCDEFG", "1234546").start()

我收到了错误:

sqlite3.OperationalError: database is locked

谢谢你, 杰

1 个答案:

答案 0 :(得分:0)

<强>回答

import threading
import time, sqlite3


class myThread(threading.Thread):

   def __init__(self, pn, icm):
       threading.Thread.__init__(self)
       self.pn = pn
       self.icm = icm

       self.con = sqlite3.connect("DB.db", check_same_thread=False)
       self.cursor = self.con.cursor()
       self.cursor.execute("CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY AUTOINCREMENT, pn VARCHAR(100), icm VARCHAR(100))")



   def run(self):

       self.cursor.execute("INSERT INTO test VALUES(NULL, '"+self.pn+"', '"+self.icm+"')")
       self.con.commit()
       self.con.close()



for i in range(0, 300):

    myThread("ABCDEFG", "12345678").start()