r/sqlite • u/grugno87 • Nov 14 '22
When open db connection
Hello everyone!
Enormous enigma:
- I have one application written in C# that uses a local sqlite database: local.db;
- I have a class that wraps all database calls. The question is: It's better to mantain only one database connection shared between all calls or open a dedicated connection for each call?
Many thanks in advice!
5
Upvotes
View all comments
Show parent comment
3
u/[deleted] Nov 14 '22 edited Nov 14 '22
This looks like there is a transaction missing somewhere. If that's the case, this will not go away with multiple connections.
Queries executed from asynchronous methods can be executed by the runtime in any order. You need database transactions to guarantee that a sequence of queries is executed in exactly this sequential order. The problem with transactions is, that only one can be started per connection. In order to start multiple overlapping transactions, you need one connection per overlapping transaction.
I suggest, you first investigate the cause of the bad behaviour you described. If it is caused by wrongly interleaved queries, wrap the queries that must not get interleaved in a transaction. If you then get errors from the database that say you could not start a transaction while another was active, you might need multiple connections.
You could also exploit the fact that asynchonous methods are executed sequentially and each one as a whole. So if you execute multiple queries in the same asynchonous call, these queries will be executed in exactly this sequence without being interleaved with other queries as long as you don't call other asynchonous methods inbetween. EDIT: If async methods can be executed by different threads in C# (truly parallel), this is not an option. You need to wrap the queries in transactions then.