Handling reconnection of MySQL (MariaDB) database without MYSQL_OPT_RECONNECT

131 views Asked by At

Currently I have this code:

Orders::Orders(QObject *parent) : QObject{parent}
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "orders");
    db.setHostName("localhost");
    db.setDatabaseName("database");
    db.setUserName("user");
    db.setPassword("password");
    db.setConnectOptions("MYSQL_OPT_RECONNECT=TRUE;");
    db.open();

    _model = new QSqlTableModel(this, db);
    _model->setTable("orders");
    _model->setEditStrategy(QSqlTableModel::OnManualSubmit);
    _model->select();
}

that runs on Ubuntu 22.10, Qt 6.4.0 and MariaDB v15.1. At runtime I get this warning:

WARNING: MYSQL_OPT_RECONNECT is deprecated and will be removed in a future version.

I read here they decided to remove the autoconnection feature completely. I also searched in other questions, like this and this, but they just focus about the warning itself.

I'm fine I can remove the option, but I don't understand how I should handle the reconnection then.

For example, this is one of my functions that rely on the database access:

void Orders::setOrderState(QString machine, QString id, DbOrderStates state)
{
    QSqlDatabase db = QSqlDatabase::database("orders");
    QString sql = QString("UPDATE orders SET states_id=:state WHERE id=:id AND machine=:machine");
    QSqlQuery query(db);
    query.prepare(sql);
    query.bindValue(":state", static_cast<int>(state));
    query.bindValue(":id", id);
    query.bindValue(":machine", machine);
    query.exec();
}

When I execute this function I want to be sure the database is connected. What am I supposed to do? I have to check the return value of prepare() and if it fails I have to reconnect to the database blocking the execution of this function?

I didn't find a signal from QSqlDatabase that tells me when the connection drops.

Also, I learnt I cannot use QSqlDatabase::isOpen() since it just returns if the database was opened, not the connection is still open at the moment of the call.

0

There are 0 answers