How to make Mysql dabase connection in multiple thread?



  • Hello. Im a beginner so it would be stupid question let me say sorry first.

    Background:
    I have to make multiple db connection. One thread works regulary searching table to show. Main thread works searching table if user requests. also each thread search table in different database. (ip, port, user, password are same)

    Problem:
    Now Im trying to make multiple connection. However, it doesnt work properly. if I use addDatabase function like QSqlDatabase db2 = QSqlDatabase::addDatabase("QMYSQL", "Other"); db is valid but I got error message. The message said QSqlQuery::exec: database not open.

    my develope environment:
    QT5.0.2, mingw4.7, windows8

    code:

    thread:
    @
    void dThread::run()
    {
    qDebug() << " database Thread Start";

    sleep(2);
    db_mutex.lock();
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "Other");
    //db = QSqlDatabase::database("first");
    qDebug() << db.isValid();
    
    db.setHostName("1.1.1.1");
    db.setPort(3306);
    db.setDatabaseName("a");
    db.setUserName("myid");
    db.setPassword("mypass");
    
    if(!db.open())
    {
        qDebug() << db.lastError().text();
    }
    db_mutex.unlock();
    
    db_mutex.lock();
    
    QSqlQuery query;
    query.exec&#40;"SELECT * FROM info"&#41;;
    while(query.next())
        qDebug() << query.value(0).toString();
    
    db.close();
    db_mutex.unlock();
    

    }
    @

    main:
    @
    int main(int argc, char *argv[])
    {

    QCoreApplication a(argc, argv);
    
    dThread dbrun;
    dbrun.start();
    
    db_mutex.lock();
    QSqlDatabase db2 = QSqlDatabase::addDatabase("QMYSQL");
    db2.setHostName("1.1.1.1");
    db2.setPort(3306);
    db2.setDatabaseName("b");
    db2.setUserName("myid");
    db2.setPassword("mypass");
    
    if(!db2.open())
    {
        qDebug() << db2.lastError().text();
    }
    
    QSqlQuery query2;
    query2.exec&#40;"SELECT * FROM info2"&#41;;
    
    while(query2.next())
    {
        qDebug() << query2.value(1).toString();
    }
    
    db2.close();
    
    db_mutex.unlock();
    
    return a.exec&#40;&#41;;
    

    }
    @

    if you have any idea, please give me advice.



  • Oh my god... very simple mistake - - . I changed QsqlQuery query(db); and it works...


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.