What happens if you transfer the database connection to a function that will work in another thread, and close the connection in the main thread? Will the connection be closed if you use with-statement?

A thread function that uses a database connection to read and write.

def post(db, states, user_list) 

Work with database:

 class SQLighter: def __init__(self, database=config.database_name): self.connection = sqlite3.connect(database) self.cursor = self.connection.cursor() def close(self): """ Закрываем текущее соединение с БД """ self.connection.close() def __enter__(self): return self def __exit__(self, Type, Value, Trace): self.close() 

I open the connection in the main process:

 with SQLighter() as db: pub_thread = Thread(target=post, args=(db, states_for_thread, user_ids)) pub_thread.start() # do other work 

How, then, will the post function work? I use SQLite and Python3 database

  • Close and get an error. - Sergey Gornostaev
  • @SergeyGornostaev Yes, I got an error. Thanks for the answer. The following question has matured. What is the best way to do - open one connection for the entire execution time of the post function or inside it, pull other functions that open a connection, do work and close the connection to the database? - chopchopa
  • It is impossible to give a definite answer, depending on many factors. - Sergey Gornostaev

1 answer 1

In this case, there will be an error at startup - it is impossible to interact with SQLite from different threads.

sqlite3.ProgrammingError: SQLite objects created in thread id 14612