requested database does not belong to the calling thread
-
Hello,
I am getting this error.
QSqlDatabasePrivate::database: requested database does not belong to the calling thread
In my application with database, I have 5 tables. I am using two tables with one thread (with plugins to application) and another three tables with second thread from same application.
is this a problem due to same connection name for both thread? or something else?
thanks.
-
Hi,
You need to create one connection per thread directly in the thread where you will use it.
-
Give each thread's connection a unique name. You can use the thread id for that for example.
-
I know this is an old topic but I've decided to leave a comment anyway, hopefully someone will respond.
I have a mysql database connection pool implemented with QSqlDatabase like this:
- On startup, I open N database connections from the main thread
- During the application lifetime, there will be M long living threads
- When a thread needs database access it will synchronise access to the db pool and obtain a free connection (connection that no other thread has taken). That connection cannot be used by another thread, so there is no race condition. After it is done, it will mark the connection as free.
Since number of threads in this case is usually higher than max. allowed number of connections, this enables me to have 100 threads using 10 mysql connections which are opened all the time.
This worked well with Qt 5.9, but with Qt 5.15 I get the same error that "requested database does not belong to the calling thread".
I understand the motives for this, but what are the alternatives to my implementation?
These are the alternatives that came to mind, but they have their own issues:
- Keeping one persistent connection per thread would lead me to having too many connections
- Opening a connection only when thread needs it would slow things down, since each query would have to first open the connection, execute, and then close it. With the current implementation, an already opened connection is used.
-
@UndeadBan said in requested database does not belong to the calling thread:
I understand the motives for this, but what are the alternatives to my implementation?
Open the connection in the thread you're using it.
-
@Christian-Ehrlicher Thank you for the response. Yeah, I understand that the connection will have to be opened from the thread where it's used. But having for example 100 threads where on average 10 of them are working with a database forces me to either have 100 connections, or frequently open and close connections. With the previous implementation, I could rotate 10 established connections between threads without the overhead of frequent open/close.
-
@drlaplace
What *solution"? As @Christian-Ehrlicher wrote aboveOpen the connection in the thread you're using it.
It's no different now from that/how it was.