1

I have a multi threaded Qt application which has multiple threads accessing a single database. Am I required create separate QSqlDatabase connections for performing SELECT / INSERT / UPDATE in each thread?

From Qt documentation, I am unable to understand if the following guideline is discouraging the above approach I suggested:

"A connection can only be used from within the thread that created it. Moving connections between threads or creating queries from a different thread is not supported."

I have practically tried using the same connection in my multiple QThreads and all works fine practically but wanted to understand if its the correct thing to do.

FYI, I am using sqlite3 from within Qt (using Qtsql API) which I understand supports serialized mode by default: https://www.sqlite.org/threadsafe.html

The reason I want to use the same connection name in multiple threads is because when I tried using different connections to the same database on multiple threads and performed SELECT / INSERT / UPDATE, I got database locked issue quite frequently. However, on using the same connection in multiple threads, this issue got eliminated completely.

Kindly guide on the same.

Regards,

Saurabh Gandhi

1
  • maybe create a wrapper class that has some slots to insert/update/delete and have it in its own thread Commented Jul 28, 2016 at 13:58

1 Answer 1

2

The documentation is not merely discouraging it, it flatly states that you must not do it (emphasis mine):

A connection can only be used from within the thread that created it.

So, no, you can't use one connection from multiple threads. It might happen to work, but it's not guaranteed to work, and you're invoking what amounts to undefined behavior. It's not guaranteed to crash either, mind you.

You need to either:

  1. Serialize the access to the database on your end, or

  2. Change the connection parameters so that locks don't reject a query but block until the database becomes available. I'm not quite sure what the database locked "issue" is: you should never see that error code (I presume it is SQLITE_LOCKED) if you actually use multiple connections. Sqlite 3 can be easily used from multiple threads, it shouldn't require any effort on your end other than enabling multithreading and using separate connections.

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.