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. Connecting to Database in Qt
Forum Updated to NodeBB v4.3 + New Features

Connecting to Database in Qt

Scheduled Pinned Locked Moved Solved General and Desktop
18 Posts 4 Posters 2.3k Views 1 Watching
  • 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.
  • Swati777999S Swati777999

    Hi All,

    Hope you're doing well.

    I have a doubt regarding connecting a DB to Qt.
    In this link https://doc.qt.io/qt-5/sql-connecting.html

    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");

    Which kind of file is "QMYSQL" written above?

    I've data in Excel files. Once I get the answer to the above question, I will be able to convert .xsls file into the required typ e for processing.

    Thanks in advance!

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

    @Swati777999 said in Connecting to Database in Qt:

    Which kind of file is "QMYSQL" written above?

    This is not a file. This tells Qt to connect to a MySQL server.

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

    Swati777999S 1 Reply Last reply
    0
    • jsulmJ jsulm

      @Swati777999 said in Connecting to Database in Qt:

      Which kind of file is "QMYSQL" written above?

      This is not a file. This tells Qt to connect to a MySQL server.

      Swati777999S Offline
      Swati777999S Offline
      Swati777999
      wrote on last edited by
      #3

      @jsulm ohh.. is it possible to connect to SQLite in the same way as MYSQL ; written below
      QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); ?

      db.setHostName("bigblue"); // **where to get this name?**
      db.setDatabaseName("flightdb"); 
      db.setUserName("acarlson");
      db.setPassword("1uTbSbAs");
      bool ok = db.open();
      

      Any help will appreciated!

      “ In order to be irreplaceable, one must always be different” – Coco Chanel

      jsulmJ 1 Reply Last reply
      0
      • Swati777999S Swati777999

        @jsulm ohh.. is it possible to connect to SQLite in the same way as MYSQL ; written below
        QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); ?

        db.setHostName("bigblue"); // **where to get this name?**
        db.setDatabaseName("flightdb"); 
        db.setUserName("acarlson");
        db.setPassword("1uTbSbAs");
        bool ok = db.open();
        

        Any help will appreciated!

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

        @Swati777999 Take a look at http://katecpp.github.io/sqlite-with-qt/
        SQLite uses a file to store the data, so there is no host name involved. Instead you specify the file:

        m_db = QSqlDatabase::addDatabase("QSQLITE");
        m_db.setDatabaseName(path);
        

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

        Swati777999S 2 Replies Last reply
        3
        • jsulmJ jsulm

          @Swati777999 Take a look at http://katecpp.github.io/sqlite-with-qt/
          SQLite uses a file to store the data, so there is no host name involved. Instead you specify the file:

          m_db = QSqlDatabase::addDatabase("QSQLITE");
          m_db.setDatabaseName(path);
          
          Swati777999S Offline
          Swati777999S Offline
          Swati777999
          wrote on last edited by
          #5

          @jsulm Thanks for the help.

          Strangely, I had bookmarked this page a few months ago, this link just slipped my mind!

          “ In order to be irreplaceable, one must always be different” – Coco Chanel

          1 Reply Last reply
          0
          • jsulmJ jsulm

            @Swati777999 Take a look at http://katecpp.github.io/sqlite-with-qt/
            SQLite uses a file to store the data, so there is no host name involved. Instead you specify the file:

            m_db = QSqlDatabase::addDatabase("QSQLITE");
            m_db.setDatabaseName(path);
            
            Swati777999S Offline
            Swati777999S Offline
            Swati777999
            wrote on last edited by
            #6

            @jsulm I want to show the result of a query in my centralWidget. Is it possible through the following codes?
            QLabel *label = new QLabel(this);

            QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
            db.setDatabaseName("C:/Users/swati/Desktop/TestData.db");
            db.exec ("Select * from TestData");
            label->setText("db.exec ("Select * from TestData")");
            setCentralWidget(label);

            How to display the result of SQL query in the centralWidget of the mainWindow?

            Any help will be appreciated!
            Regards
            Swati

            “ In order to be irreplaceable, one must always be different” – Coco Chanel

            Pl45m4P 1 Reply Last reply
            0
            • Swati777999S Swati777999

              @jsulm I want to show the result of a query in my centralWidget. Is it possible through the following codes?
              QLabel *label = new QLabel(this);

              QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE");
              db.setDatabaseName("C:/Users/swati/Desktop/TestData.db");
              db.exec ("Select * from TestData");
              label->setText("db.exec ("Select * from TestData")");
              setCentralWidget(label);

              How to display the result of SQL query in the centralWidget of the mainWindow?

              Any help will be appreciated!
              Regards
              Swati

              Pl45m4P Offline
              Pl45m4P Offline
              Pl45m4
              wrote on last edited by Pl45m4
              #7

              @Swati777999 said in Connecting to Database in Qt:

              How to display the result of SQL query in the centralWidget of the mainWindow?

              Depends on what your centralWidget is...

              The way you do this currently, is definitely wrong. It would show the text if your query as label.

              Have a look here:

              • https://doc.qt.io/qt-5/sql-sqlstatements.html

              If debugging is the process of removing software bugs, then programming must be the process of putting them in.

              ~E. W. Dijkstra

              Swati777999S 1 Reply Last reply
              0
              • Pl45m4P Pl45m4

                @Swati777999 said in Connecting to Database in Qt:

                How to display the result of SQL query in the centralWidget of the mainWindow?

                Depends on what your centralWidget is...

                The way you do this currently, is definitely wrong. It would show the text if your query as label.

                Have a look here:

                • https://doc.qt.io/qt-5/sql-sqlstatements.html
                Swati777999S Offline
                Swati777999S Offline
                Swati777999
                wrote on last edited by
                #8

                @Pl45m4
                I checked the documentation which

                For viewing the data from SQL query in tabular form, what to use whether SQL Model Class or QTableview?

                “ In order to be irreplaceable, one must always be different” – Coco Chanel

                jsulmJ 1 Reply Last reply
                0
                • Swati777999S Swati777999

                  @Pl45m4
                  I checked the documentation which

                  For viewing the data from SQL query in tabular form, what to use whether SQL Model Class or QTableview?

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

                  @Swati777999 said in Connecting to Database in Qt:

                  what to use whether SQL Model Class or QTableview?

                  Both.
                  Please see how it is done here: https://doc.qt.io/qt-5/qsqltablemodel.html

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

                  Swati777999S 1 Reply Last reply
                  0
                  • jsulmJ jsulm

                    @Swati777999 said in Connecting to Database in Qt:

                    what to use whether SQL Model Class or QTableview?

                    Both.
                    Please see how it is done here: https://doc.qt.io/qt-5/qsqltablemodel.html

                    Swati777999S Offline
                    Swati777999S Offline
                    Swati777999
                    wrote on last edited by
                    #10

                    @jsulm said in Connecting to Database in Qt:

                    @Swati777999 said in Connecting to Database in Qt:

                    what to use whether SQL Model Class or QTableview?

                    Both.
                    Please see how it is done here: https://doc.qt.io/qt-5/qsqltablemodel.html

                    I used this strategy but I am not getting anything in my main window. :(

                    “ In order to be irreplaceable, one must always be different” – Coco Chanel

                    jsulmJ 1 Reply Last reply
                    0
                    • Swati777999S Swati777999

                      @jsulm said in Connecting to Database in Qt:

                      @Swati777999 said in Connecting to Database in Qt:

                      what to use whether SQL Model Class or QTableview?

                      Both.
                      Please see how it is done here: https://doc.qt.io/qt-5/qsqltablemodel.html

                      I used this strategy but I am not getting anything in my main window. :(

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

                      @Swati777999 Then you are doing something wrong and should provide more information to get meaningful answer.
                      Best would be related code.

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

                      Swati777999S 1 Reply Last reply
                      0
                      • jsulmJ jsulm

                        @Swati777999 Then you are doing something wrong and should provide more information to get meaningful answer.
                        Best would be related code.

                        Swati777999S Offline
                        Swati777999S Offline
                        Swati777999
                        wrote on last edited by Swati777999
                        #12

                        @jsulm

                        #include "dbmanager.h"

                        DbManager::DbManager(const QString &path)
                        { Q_UNUSED(path);
                        m_db = QSqlDatabase::addDatabase("QSQLITE");
                        m_db.setDatabaseName("C:/Users/ss/Desktop/TestData.db");

                        if (!m_db.open())
                        {
                        qDebug() << "Error: connection with database failed";
                        }
                        else
                        {
                        qDebug() << "Database: connection ok";
                        }
                        }
                        bool DbManager::addEntry(const QString &name)
                        {
                        bool success = false;
                        QSqlQuery query;
                        query.prepare("INSERT INTO TestData VALUES (:time)");
                        query.bindValue(":time, time);
                        if(query.exec())
                        {
                        success = true;
                        }
                        else
                        {
                        qDebug() << "addtemperature error:"
                        << query.lastError();
                        }

                        return success;
                        qDebug() << query.isValid();

                        QSqlQueryModel model;
                           model.setQuery("SELECT * FROM TestData");
                        
                         for (int i = 0; i < model.rowCount(); ++i) {
                            int id = model.record(i).value("id").toInt();
                           QString name = model.record(i).value("time").toString();
                           qDebug() << id << time;
                           }
                        
                           QLabel *labelExp = new QLabel(this);
                           labelExp->setFrameStyle(QFrame::Panel | QFrame::Sunken);
                           labelExp->setText("first line\nsecond line");
                           labelExp->setAlignment(Qt::AlignBottom | Qt::AlignRight);
                        
                           //Named binding
                           QSqlQuery query1;
                           query1.prepare("INSERT INTO TestData (time,temperature) VALUES (:time, "
                                          ":temperature)");
                           query1.bindValue(":time","2020-11-31 10:19:38");
                           query1.bindValue(":temperature", 27.4);
                           query1.exec();
                        
                           //Positional Binding
                           QSqlQuery query2;
                           query2.prepare("INSERT INTO TestData (time,temperature) VALUES (?, ?, )");
                           query2.addBindValue("2010-06-31 12:08:35");
                           query2.addBindValue(30.6);
                           query2.exec();
                        
                           QSqlQueryModel *model1 = new QSqlQueryModel;
                              model1->setQuery("SELECT time, temperature FROM TestData");
                              model1->setHeaderData(0, Qt::Horizontal, tr("Time"));
                              model1->setHeaderData(1, Qt::Horizontal, tr("Temperature"));
                        
                              QTableView *view = new QTableView;
                              view->setModel(model1);
                              view->show();
                        
                              model1->setHeaderData(0, Qt::Horizontal, QObject::tr("Time"));
                              model1->setHeaderData(1, Qt::Horizontal, QObject::tr("Temperature"));
                        

                        }

                        “ In order to be irreplaceable, one must always be different” – Coco Chanel

                        jsulmJ 1 Reply Last reply
                        0
                        • Swati777999S Swati777999

                          @jsulm

                          #include "dbmanager.h"

                          DbManager::DbManager(const QString &path)
                          { Q_UNUSED(path);
                          m_db = QSqlDatabase::addDatabase("QSQLITE");
                          m_db.setDatabaseName("C:/Users/ss/Desktop/TestData.db");

                          if (!m_db.open())
                          {
                          qDebug() << "Error: connection with database failed";
                          }
                          else
                          {
                          qDebug() << "Database: connection ok";
                          }
                          }
                          bool DbManager::addEntry(const QString &name)
                          {
                          bool success = false;
                          QSqlQuery query;
                          query.prepare("INSERT INTO TestData VALUES (:time)");
                          query.bindValue(":time, time);
                          if(query.exec())
                          {
                          success = true;
                          }
                          else
                          {
                          qDebug() << "addtemperature error:"
                          << query.lastError();
                          }

                          return success;
                          qDebug() << query.isValid();

                          QSqlQueryModel model;
                             model.setQuery("SELECT * FROM TestData");
                          
                           for (int i = 0; i < model.rowCount(); ++i) {
                              int id = model.record(i).value("id").toInt();
                             QString name = model.record(i).value("time").toString();
                             qDebug() << id << time;
                             }
                          
                             QLabel *labelExp = new QLabel(this);
                             labelExp->setFrameStyle(QFrame::Panel | QFrame::Sunken);
                             labelExp->setText("first line\nsecond line");
                             labelExp->setAlignment(Qt::AlignBottom | Qt::AlignRight);
                          
                             //Named binding
                             QSqlQuery query1;
                             query1.prepare("INSERT INTO TestData (time,temperature) VALUES (:time, "
                                            ":temperature)");
                             query1.bindValue(":time","2020-11-31 10:19:38");
                             query1.bindValue(":temperature", 27.4);
                             query1.exec();
                          
                             //Positional Binding
                             QSqlQuery query2;
                             query2.prepare("INSERT INTO TestData (time,temperature) VALUES (?, ?, )");
                             query2.addBindValue("2010-06-31 12:08:35");
                             query2.addBindValue(30.6);
                             query2.exec();
                          
                             QSqlQueryModel *model1 = new QSqlQueryModel;
                                model1->setQuery("SELECT time, temperature FROM TestData");
                                model1->setHeaderData(0, Qt::Horizontal, tr("Time"));
                                model1->setHeaderData(1, Qt::Horizontal, tr("Temperature"));
                          
                                QTableView *view = new QTableView;
                                view->setModel(model1);
                                view->show();
                          
                                model1->setHeaderData(0, Qt::Horizontal, QObject::tr("Time"));
                                model1->setHeaderData(1, Qt::Horizontal, QObject::tr("Temperature"));
                          

                          }

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

                          @Swati777999 said in Connecting to Database in Qt:

                          QSqlQueryModel model;

                          Your model is a local variable and is destroyed as soon as it goes out of scope.
                          And please format you code properly.

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

                          Pl45m4P Swati777999S 2 Replies Last reply
                          3
                          • jsulmJ jsulm

                            @Swati777999 said in Connecting to Database in Qt:

                            QSqlQueryModel model;

                            Your model is a local variable and is destroyed as soon as it goes out of scope.
                            And please format you code properly.

                            Pl45m4P Offline
                            Pl45m4P Offline
                            Pl45m4
                            wrote on last edited by
                            #14

                            @jsulm

                            For whatever reason there are two models... QSqlQueryModel model and QSqlQueryModel* model1


                            If debugging is the process of removing software bugs, then programming must be the process of putting them in.

                            ~E. W. Dijkstra

                            Swati777999S 1 Reply Last reply
                            0
                            • jsulmJ jsulm

                              @Swati777999 said in Connecting to Database in Qt:

                              QSqlQueryModel model;

                              Your model is a local variable and is destroyed as soon as it goes out of scope.
                              And please format you code properly.

                              Swati777999S Offline
                              Swati777999S Offline
                              Swati777999
                              wrote on last edited by
                              #15

                              @jsulm I didn't get your point clearly and how to format the code; do you mean looking after the indentation/ improving the readability of the codes?

                              “ In order to be irreplaceable, one must always be different” – Coco Chanel

                              JonBJ jsulmJ 2 Replies Last reply
                              0
                              • Pl45m4P Pl45m4

                                @jsulm

                                For whatever reason there are two models... QSqlQueryModel model and QSqlQueryModel* model1

                                Swati777999S Offline
                                Swati777999S Offline
                                Swati777999
                                wrote on last edited by
                                #16

                                @Pl45m4 I was trying to see how QSqlQuery and QSqlQueryModel are different from each other, no other reason apart from that.

                                “ In order to be irreplaceable, one must always be different” – Coco Chanel

                                1 Reply Last reply
                                0
                                • Swati777999S Swati777999

                                  @jsulm I didn't get your point clearly and how to format the code; do you mean looking after the indentation/ improving the readability of the codes?

                                  JonBJ Offline
                                  JonBJ Offline
                                  JonB
                                  wrote on last edited by
                                  #17

                                  @Swati777999 said in Connecting to Database in Qt:

                                  I didn't get your point clearly and how to format the code; do you mean looking after the indentation/ improving the readability of the codes?

                                  When pasting code please select it all and use the the </> Code button:

                                  so it comes out like this
                                  with ``` above & below it in your post
                                  

                                  As for your code. addEntry() at least does little --- most of the code is not executed --- since you have an unconditional return statement before most of the body. If people are supposed to look at this for you, you should really clear it up a lot before posting.

                                  1 Reply Last reply
                                  1
                                  • Swati777999S Swati777999

                                    @jsulm I didn't get your point clearly and how to format the code; do you mean looking after the indentation/ improving the readability of the codes?

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

                                    @Swati777999 said in Connecting to Database in Qt:

                                    I didn't get your point clearly

                                    We are talking about absolute C++ basics now! Please learn those!

                                    bool DbManager::addEntry(const QString &name)
                                    {
                                    ...
                                    QSqlQueryModel model;
                                    ...
                                    }
                                    

                                    In the code above "model" only exists inside DbManager::addEntry. As soon as DbManager::addEntry is done "mode" goes out of scope and is deleted!
                                    Also, I see that you do "return success;" before you create your model - how can this work at all?!

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

                                    1 Reply Last reply
                                    2

                                    • Login

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