How Can I use db in threads? Requested database does not belong to the calling thread.

  • How to use database in threads? I create instance of db in main thread and give threads pointers. But it crashes, also I tried to create instance in Thread, it doesn't work. How Can I use db in threads?

    #ifndef THREAD_H
    #define THREAD_H
    #include <QThread>
    #include <QTcpSocket>
    #include <QRegularExpression>
    #include "dbmanager.h"
    class MyThread : public QThread
        explicit MyThread(qintptr ID, QObject *parent = nullptr);
        void run();
        void error(QTcpSocket::SocketError socketerror);
      public slots:
        void readyRead();
        void disconnected();
        QTcpSocket *socket;
        qintptr socketDescriptor;
        DB_Manager * db;
        void analysis(QString httpRequest, QString& method, QString& uri, QString& body);
    #endif // THREAD_H
    void MyThread::run()
      socket = new QTcpSocket();
      if (!socket->setSocketDescriptor(this->socketDescriptor) )
        emit error (socket->error());
      connect(socket, SIGNAL(readyRead()), this, SLOT(readyRead()),Qt::DirectConnection );
      connect(socket, SIGNAL(disconnected()), this, SLOT(disconnected()));
    void HttpServer::incomingConnection(qintptr socketDescriptor)
        MyThread *thread = new MyThread(socketDescriptor, this);
        connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));

    In MyThread function:

    QJsonDocument dbody = QJsonDocument::fromJson(body.toLocal8Bit());
                QString password = dbody.object()["password"].toString();
                int id = db->getIdByLog(tname.toStdString(), password.toStdString());
                if(id != 0)
                    sendLog(true, id);
                    sendLog(false, 0);

  • Lifetime Qt Champion


    What is DB_Manager ?
    Where do you allocate it ?
    How is it implemented ?

Log in to reply

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