db connection issue



  • 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.


  • Lifetime Qt Champion

    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.



  • 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?


  • Lifetime Qt Champion

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

    How are you using the database stuff in that class ?



  • 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.


  • Moderators

    @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.



  • @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.


  • Qt Champions 2016

    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.



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


  • Qt Champions 2016

    @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


  • Lifetime Qt Champion

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



  • @mrjj
    Thank you for your help. This worked.


Log in to reply
 

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