Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 views
in Technique[技术] by (71.8m points)

c++ - Is there any qt signal for sql database change?

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...