1

I would like to make a program with multiple threads. In each thread should be a database INSERT.

EDIT

But now I get the same error after a time

My code:

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()

I get the ERROR:

sqlite3.OperationalError: database is locked

Thank you, Jay

4
  • What went wrong? Commented Jun 8, 2017 at 23:08
  • @tdelaney Edited Commented Jun 8, 2017 at 23:16
  • As the error message says. You close the database with con.close(). That is why it cannot write / execute query on your database. You need to reconnect, usually with sqlite3.connect(). Commented Jun 8, 2017 at 23:17
  • You can not do multiple writes to an SQLite database at the same time. Commented Jun 9, 2017 at 1:58

1 Answer 1

2

Answered

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.