Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. db connection issue
Forum Update on Monday, May 27th 2025

db connection issue

Scheduled Pinned Locked Moved General and Desktop
12 Posts 4 Posters 2.5k Views
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G Offline
    G Offline
    gabor53
    wrote on last edited by
    #1

    Hi,
    I created a db connection in main.cpp:

    #include "mainwindow.h"
    #include "ui_display.h"
    #include <QApplication>
    
    int main(int argc, char *argv[])
    {
        QApplication a(argc, argv);
    
    
        QSqlDatabase db;
        QString fileQstring = "C:/Programming/Projects/FolkFriends_1_0/db.db";
    
        db = QSqlDatabase::addDatabase ("QSQLITE");
        db.setDatabaseName (fileQstring);
        qDebug() << "Connection Display created in main.cpp. ";
    
        bool OK = db.open ();
    
        if(OK == true)
            {
                qDebug() << "The db (MainWindow) is open!";
            }
        else
            {
                qDebug() << "The db (MainWindow) is not open!";
            }
    
        if(!db.open ())
            {
                qDebug() << "The database (db) is NOT open!" << db.lastError ();
    
            }
        db.open();
        MainWindow w;
    
    
        w.show();
    
        return a.exec();
    }
    
    

    It works in mainwindow. Is it possible to use this connection in the rest of the classes in the project? None of the other classes seems to be able to see this connection. Thank you.

    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      Watch out you are calling open several times. Once is enough.

      Since you are using the default connection you don't need to do anything special, just use QSqlQuery and friends in your other classes.

      Interested in AI ? www.idiap.ch
      Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

      G 1 Reply Last reply
      1
      • SGaistS SGaist

        Hi,

        Watch out you are calling open several times. Once is enough.

        Since you are using the default connection you don't need to do anything special, just use QSqlQuery and friends in your other classes.

        G Offline
        G Offline
        gabor53
        wrote on last edited by
        #3

        Hi @SGaist

        I made the following changes in additem.h:

        namespace Ui
        {
        class Additem;
        }
        
        class Additem : public QDialog
        {
            Q_OBJECT
        
            friend class MainWindow;
        
        public:
            explicit Additem(QWidget *parent = 0);
            ~Additem();
        

        I added friend class MainWindow; and changed main.cpp to this:

            QSqlDatabase db;
            QString fileQstring = "C:/Programming/Projects/FolkFriends_1_0/db.db";
        
            db = QSqlDatabase::addDatabase ("QSQLITE");
            db.setDatabaseName (fileQstring);
            qDebug() << "Connection Display created in main.cpp. ";
        
            bool OK = db.open ();
        
            if(OK == true)
                {
                    qDebug() << "The db (MainWindow) is open!";
                }
            else
                {
                    qDebug() << "The db (MainWindow) is not open!";
                }
        
        

        I still can't use the connection in Additem. Is my friend class incorrect?

        1 Reply Last reply
        0
        • SGaistS Offline
          SGaistS Offline
          SGaist
          Lifetime Qt Champion
          wrote on last edited by
          #4

          There's not reason to make MainWindow a friend of Additem.

          How are you using the database stuff in that class ?

          Interested in AI ? www.idiap.ch
          Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

          1 Reply Last reply
          0
          • G Offline
            G Offline
            gabor53
            wrote on last edited by
            #5

            MainWindow just uses the db connection created in main.cpp. The main problem is that I can't use the connection created in main.cpp in additem. It keeps giving me driver not koaded error.

            jsulmJ 1 Reply Last reply
            0
            • G gabor53

              MainWindow just uses the db connection created in main.cpp. The main problem is that I can't use the connection created in main.cpp in additem. It keeps giving me driver not koaded error.

              jsulmJ Offline
              jsulmJ Offline
              jsulm
              Lifetime Qt Champion
              wrote on last edited by
              #6

              @gabor53 Could you please show how you're using the db connection in Additem?

              A note: Additem is a really bad name for a class! "add item" is an action, a class is usually a "thing" that can have actions.

              https://forum.qt.io/topic/113070/qt-code-of-conduct

              G 1 Reply Last reply
              2
              • jsulmJ jsulm

                @gabor53 Could you please show how you're using the db connection in Additem?

                A note: Additem is a really bad name for a class! "add item" is an action, a class is usually a "thing" that can have actions.

                G Offline
                G Offline
                gabor53
                wrote on last edited by
                #7

                @jsulm
                Here is the wayI use it:

                        QSqlQuery query_what ("SELECT What FROM What_Table ORDER BY What asc",db);
                
                        if(query_what.isActive ()==false)
                            {
                                QMessageBox::critical (this,"Error 1004","The database can not be reached! Try again later.");
                            }
                
                        while (query_what.next ())
                            {
                                whatItem = query_what.value (0).toString ();
                                ui->What_Combo->addItem (whatItem);
                            }
                
                    }
                
                    if (what != "")
                        {
                            ui->What_Combo->setCurrentText (what);
                        }
                
                    whatChosen = ui->What_Combo->currentText ();
                
                    connect(ui->What_Combo,SIGNAL(currentIndexChanged(int)),this,SLOT(processcombo(int)));
                

                Thank you for the naming note.

                1 Reply Last reply
                0
                • mrjjM Offline
                  mrjjM Offline
                  mrjj
                  Lifetime Qt Champion
                  wrote on last edited by mrjj
                  #8

                  Hi
                  have you tried without using DB at all?

                  QSqlQuery query_what ("SELECT What FROM What_Table ORDER BY What asc",db);

                  QSqlQuery can use the default db. and hence no need to specify it.

                  G 1 Reply Last reply
                  2
                  • mrjjM mrjj

                    Hi
                    have you tried without using DB at all?

                    QSqlQuery query_what ("SELECT What FROM What_Table ORDER BY What asc",db);

                    QSqlQuery can use the default db. and hence no need to specify it.

                    G Offline
                    G Offline
                    gabor53
                    wrote on last edited by
                    #9

                    @mrjj
                    This is what I tried. Can you please show me an example how to do it without the db? Thank you.

                    mrjjM 1 Reply Last reply
                    0
                    • G gabor53

                      @mrjj
                      This is what I tried. Can you please show me an example how to do it without the db? Thank you.

                      mrjjM Offline
                      mrjjM Offline
                      mrjj
                      Lifetime Qt Champion
                      wrote on last edited by
                      #10

                      @gabor53
                      Ok, maybe there is something in your use case im overlooking ?

                      bool createConnection() {
                        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
                        db.setDatabaseName(":memory:");
                        if (!db.open()) {
                          QMessageBox::critical(0, qApp->tr("Cannot open database"), "Click Cancel to exit.", QMessageBox::Cancel);
                          return false;
                        }
                        QSqlQuery query;
                        qDebug() << "table:" <<   query.exec("create table person (id int primary key, "
                                                             "firstname varchar(20), lastname varchar(20), num int )");
                        query.exec("insert into person values(101, 'Dennis', 'Young','1')");
                        query.exec("insert into person values(102, 'Christine', 'Holand','2')");
                        query.exec("insert into person values(103, 'Lars junior', 'Gordon','4')");
                        query.exec("insert into person values(104, 'Roberto', 'Robitaille','5')");
                        query.exec("insert into person values(105, 'Maria', 'Papadopoulos','3')");
                        return true;
                      }
                      
                      void MainWindow::on_pushButton_released() {
                        createConnection();
                      
                        QSqlQuery query;
                        int ok = query.prepare("SELECT * from person ");
                        if (!ok) qDebug() << "prepare failed";
                        query.exec();
                        while (query.next()) {
                          QString name = query.value(1).toString(); // col 1 = name
                          ui->listWidget->addItem(name);
                        }
                      }
                      

                      full project.
                      https://www.dropbox.com/s/nqm2jwiyyakmmo8/db.zip?dl=0

                      G 1 Reply Last reply
                      4
                      • SGaistS Offline
                        SGaistS Offline
                        SGaist
                        Lifetime Qt Champion
                        wrote on last edited by
                        #11

                        On a side note, you really should take a look at the QSql module examples. They all use only the default connection.

                        Interested in AI ? www.idiap.ch
                        Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                        1 Reply Last reply
                        1
                        • mrjjM mrjj

                          @gabor53
                          Ok, maybe there is something in your use case im overlooking ?

                          bool createConnection() {
                            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
                            db.setDatabaseName(":memory:");
                            if (!db.open()) {
                              QMessageBox::critical(0, qApp->tr("Cannot open database"), "Click Cancel to exit.", QMessageBox::Cancel);
                              return false;
                            }
                            QSqlQuery query;
                            qDebug() << "table:" <<   query.exec("create table person (id int primary key, "
                                                                 "firstname varchar(20), lastname varchar(20), num int )");
                            query.exec("insert into person values(101, 'Dennis', 'Young','1')");
                            query.exec("insert into person values(102, 'Christine', 'Holand','2')");
                            query.exec("insert into person values(103, 'Lars junior', 'Gordon','4')");
                            query.exec("insert into person values(104, 'Roberto', 'Robitaille','5')");
                            query.exec("insert into person values(105, 'Maria', 'Papadopoulos','3')");
                            return true;
                          }
                          
                          void MainWindow::on_pushButton_released() {
                            createConnection();
                          
                            QSqlQuery query;
                            int ok = query.prepare("SELECT * from person ");
                            if (!ok) qDebug() << "prepare failed";
                            query.exec();
                            while (query.next()) {
                              QString name = query.value(1).toString(); // col 1 = name
                              ui->listWidget->addItem(name);
                            }
                          }
                          

                          full project.
                          https://www.dropbox.com/s/nqm2jwiyyakmmo8/db.zip?dl=0

                          G Offline
                          G Offline
                          gabor53
                          wrote on last edited by
                          #12

                          @mrjj
                          Thank you for your help. This worked.

                          1 Reply Last reply
                          1

                          • Login

                          • Login or register to search.
                          • First post
                            Last post
                          0
                          • Categories
                          • Recent
                          • Tags
                          • Popular
                          • Users
                          • Groups
                          • Search
                          • Get Qt Extensions
                          • Unsolved