Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I wrote a C++ program using Qt. some variables inside my algorithm are changed outside of my program and in a web page. every time the user changes the variable values in the web page I modify a pre-created SQL database. Now I want my code to change the variables value during run time without to stop the code. there is two options :

  1. Every n seconds check the database and retrieve the variables value -> this is not good since I have to check if database content is changed every n seconds (it might be without any change for years. Also I don't want to check if the database content is changed)

  2. Every time the database is changed my Qt program emits a signal so by catching this signal I can refresh the variables value, This seems an optimal solution and I want to write a code for this part

The C++ part of my code is:

void Update Database()
{
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("localhost");
    db.setDatabaseName("Mydataset");

    db.setUserName("user");
    db.setPassword("pass");

    if(!db.open())
    {
        qDebug()<<"Error is: "<<db.lastError();
        qFatal("Failed To Connect");
    }
    QSqlQuery qry;
    qry.exec("SELECT * from tblsystemoptions");
    QSqlRecord rec = qry.record();
    int cols = rec.count();
    qry.next();
    MCH = qry.value(0).toString();  //some global variables used in other functions
    MCh = qry.value(1).toString();
    // ... this goes on ...


}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
332 views
Welcome To Ask or Share your Answers For Others

1 Answer

QSqlDriver supports notifications which emit a signal when a specific event has occurred. To subscribe to an event just use QSqlDriver::subscribeToNotification( const QString & name ). When an event that you’re subscribing to is posted by the database the driver will emit the notification() signal and your application can take appropriate action.

db.driver()->subscribeToNotification("someEventId");

The message can be posted automatically from a trigger or a stored procedure. The message is very lightweight: nothing more than a string containing the name of the event that occurred.

You can connect the notification(const QString&)signal to your slot like:

QObject::connect(db.driver(), SIGNAL(notification(const QString&)), this, SLOT(refreshView()));

I should note that this feature is not supported by MySQL as it does not have an event posting mechanism.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...