I am doing a project that uses QSqlDatabase. And now I am using QtConcurrent (QFuture) to execute any SQL command.
Right now, every new command that run using QFuture create new QSqlDatabase connection to my Mysql server. I believe any new connection to Mysql server will have penalty about the handshake. So I have a plan to make a pool QSqlDatabase and from the documentation QSqlDatabase only able to be used by the thread who made it.
So, my idea is to make a QMap pools, which the int is the thread id and the QString is the connection name. So when I want to start a thread from threadpool using qfuture, just get the connection name from the QMap pool and get the QSqlDatabase (which this QSqlDatabase is already connected to server).
Sample code :
//this is static variable
QMap<int, QString> pool;
.....
//At the beginning of sql command to execute
if(pool.contains((int)QThread::currentThreadId()) {
db = QSqlDatabase::database(pool[(int)QThread::currentThreadId()]);
} else {
QString key = "someunique" + QString::number((int)QThread::currentThreadId());
db = QSqlDatabase::add(key)
... // some Qsql connection code
pool.insert((int)QThread::currentThreadId(), key);
}
Maybe my code above not work, but what I want to ask : is my idea will work? Or do I missed something about the QSqlDatabase?