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. Create postgreSQL database with Qt
Forum Updated to NodeBB v4.3 + New Features

Create postgreSQL database with Qt

Scheduled Pinned Locked Moved Solved General and Desktop
12 Posts 4 Posters 3.2k 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.
  • I Offline
    I Offline
    ivanicy
    wrote on 17 Feb 2022, 09:34 last edited by
    #1

    Hello!!

    I am trying to create a postgre database with Qt and then I want to check it with pgAdmin.

    Which query and which connections I have to do before to do it? I have tried this, but it doesn't work:

    m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
    
        if (m_pDatabase != nullptr) {
            m_pDatabase->setConnectOptions();
            m_pDatabase->setHostName(sServerName);
    //        m_pDatabase->setDatabaseName(sDatabaseName);
            m_pDatabase->setUserName(sUserName);
            m_pDatabase->setPassword(sPassword);
        }
    
        QSqlQuery query(*m_pDatabase);
        bool bCorrect = query.exec("CREATE DATABASE " + sDatabaseName);
        if (!bCorrect) {
            qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
            IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
            return false;
        } else {
            bCorrect = query.exec("USE " + sDatabaseName);
        }
    

    Thank you very much!!

    J 1 Reply Last reply 17 Feb 2022, 09:38
    0
    • I ivanicy
      17 Feb 2022, 10:51

      I tell more details: right now, I create the database with pgAdmin, create the tables with pgAdmin, connect to them with Qt and fill them from Qt. My goal is to create the database and tables from Qt as well, to further automate the process. This code is what has been working for me so far:

      bool CDatabaseManager::connectToDatabase(const char *sDriverName, QString sServerName, QString sDatabaseName, QString sUserName, QString sPassword)
      {
          m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
      
          if (m_pDatabase != nullptr) {
              m_pDatabase->setConnectOptions();
              m_pDatabase->setHostName(sServerName);
              m_pDatabase->setDatabaseName(sDatabaseName);
              m_pDatabase->setUserName(sUserName);
              m_pDatabase->setPassword(sPassword);
          }
      
          if (m_pDatabase->open()) {
              return true;
          } else {
              qDebug() << "[DATABASE ERROR]: Database not open." << m_pDatabase->lastError().text();
              return false;
          }
      }
      
      J Offline
      J Offline
      jsulm
      Lifetime Qt Champion
      wrote on 17 Feb 2022, 11:41 last edited by
      #10

      @ivanicy said in Create postgreSQL database with Qt:

      This code is what has been working for me so far

      So, create the database and tables now after you open the database

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

      I 1 Reply Last reply 17 Feb 2022, 13:01
      3
      • I ivanicy
        17 Feb 2022, 09:34

        Hello!!

        I am trying to create a postgre database with Qt and then I want to check it with pgAdmin.

        Which query and which connections I have to do before to do it? I have tried this, but it doesn't work:

        m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
        
            if (m_pDatabase != nullptr) {
                m_pDatabase->setConnectOptions();
                m_pDatabase->setHostName(sServerName);
        //        m_pDatabase->setDatabaseName(sDatabaseName);
                m_pDatabase->setUserName(sUserName);
                m_pDatabase->setPassword(sPassword);
            }
        
            QSqlQuery query(*m_pDatabase);
            bool bCorrect = query.exec("CREATE DATABASE " + sDatabaseName);
            if (!bCorrect) {
                qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
                IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
                return false;
            } else {
                bCorrect = query.exec("USE " + sDatabaseName);
            }
        

        Thank you very much!!

        J Offline
        J Offline
        JonB
        wrote on 17 Feb 2022, 09:38 last edited by JonB
        #2

        @ivanicy
        Where do you open the database?

        I have tried this, but it doesn't work:

        And what does your m_pDatabase->lastError().text() say?

        I 1 Reply Last reply 17 Feb 2022, 10:30
        1
        • C Offline
          C Offline
          Christian Ehrlicher
          Lifetime Qt Champion
          wrote on 17 Feb 2022, 09:42 last edited by
          #3

          And why do you hold QSqlDatabase as a pointer (and dereference a nullptr). Please read the docs on how to use QSqlDatabase.

          Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
          Visit the Qt Academy at https://academy.qt.io/catalog

          1 Reply Last reply
          1
          • J JonB
            17 Feb 2022, 09:38

            @ivanicy
            Where do you open the database?

            I have tried this, but it doesn't work:

            And what does your m_pDatabase->lastError().text() say?

            I Offline
            I Offline
            ivanicy
            wrote on 17 Feb 2022, 10:30 last edited by
            #4

            @JonB I open the database a few lines later, but it can't open it. lastError() is empty:

            [DATABASE ERROR]: ""
            
            C J 2 Replies Last reply 17 Feb 2022, 10:32
            0
            • I ivanicy
              17 Feb 2022, 10:30

              @JonB I open the database a few lines later, but it can't open it. lastError() is empty:

              [DATABASE ERROR]: ""
              
              C Offline
              C Offline
              Christian Ehrlicher
              Lifetime Qt Champion
              wrote on 17 Feb 2022, 10:32 last edited by
              #5

              @ivanicy said in Create postgreSQL database with Qt:

              I open the database a few lines later,

              Please post your code, not only some single lines.

              Qt Online Installer direct download: https://download.qt.io/official_releases/online_installers/
              Visit the Qt Academy at https://academy.qt.io/catalog

              I 1 Reply Last reply 17 Feb 2022, 10:42
              1
              • C Christian Ehrlicher
                17 Feb 2022, 10:32

                @ivanicy said in Create postgreSQL database with Qt:

                I open the database a few lines later,

                Please post your code, not only some single lines.

                I Offline
                I Offline
                ivanicy
                wrote on 17 Feb 2022, 10:42 last edited by
                #6

                @Christian-Ehrlicher Ok sorry, this is the function:

                bool CDatabaseManager::connectToDatabase(const char *sDriverName, QString sServerName, QString sDatabaseName, QString sUserName, QString sPassword)
                {
                    m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
                
                    if (m_pDatabase != nullptr) {
                        m_pDatabase->setConnectOptions();
                        m_pDatabase->setHostName(sServerName);
                //        m_pDatabase->setDatabaseName(sDatabaseName);
                        m_pDatabase->setUserName(sUserName);
                        m_pDatabase->setPassword(sPassword);
                    }
                
                    QSqlQuery query(*m_pDatabase);
                    bool bCorrect = query.exec("CREATE DATABASE " + sDatabaseName);
                    if (!bCorrect) {
                        qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
                        IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
                        return false;
                    } else {
                        bCorrect = query.exec("USE " + sDatabaseName);
                    }
                
                    bCorrect = query.exec("CREATE TABLE IF NOT EXISTS Alarms ("
                                          "alarmCode VARCHAR(10) NOT NULL,"
                                          "cameraSN VARCHAR(10),"
                                          "cameraID VARCHAR(2) NOT NULL,"
                                          "presetID VARCHAR(2) NOT NULL,"
                                          "roiID VARCHAR(2) NOT NULL,"
                                          "alarmDate DATE NOT NULL,"
                                          "alarmTime TIME NOT NULL,"
                                          "description VARCHAR(100),"
                                          "data VARCHAR(300),"
                                          "image BYTEA,"
                                          "pathVideo VARCHAR(300),"
                                          "CONSTRAINT pk_alarms PRIMARY KEY (alarmCode, cameraID, presetID, roiID, alarmDate, alarmTime));");
                
                    if (!bCorrect) {
                        qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
                        IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
                    }
                
                    bCorrect = query.exec("CREATE TABLE IF NOT EXISTS Data ("
                                          "dataCode VARCHAR(10) NOT NULL,"
                                          "cameraSN VARCHAR(10),"
                                          "cameraID VARCHAR(2) NOT NULL,"
                                          "presetID VARCHAR(2) NOT NULL,"
                                          "roiID VARCHAR(2) NOT NULL,"
                                          "dataDate DATE NOT NULL,"
                                          "dataTime TIME NOT NULL,"
                                          "description VARCHAR(100),"
                                          "data VARCHAR(300),"
                                          "CONSTRAINT pk_data PRIMARY KEY (dataCode, cameraID, presetID, roiID, dataDate, dataTime));");
                
                    if (!bCorrect) {
                        qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
                        IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
                    }
                
                    if (m_pDatabase->open()) {
                        return true;
                    } else {
                        qDebug() << "[DATABASE ERROR]: Database not open." << m_pDatabase->lastError().text();
                        return false;
                    }
                }
                
                J 1 Reply Last reply 17 Feb 2022, 10:43
                0
                • I ivanicy
                  17 Feb 2022, 10:42

                  @Christian-Ehrlicher Ok sorry, this is the function:

                  bool CDatabaseManager::connectToDatabase(const char *sDriverName, QString sServerName, QString sDatabaseName, QString sUserName, QString sPassword)
                  {
                      m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
                  
                      if (m_pDatabase != nullptr) {
                          m_pDatabase->setConnectOptions();
                          m_pDatabase->setHostName(sServerName);
                  //        m_pDatabase->setDatabaseName(sDatabaseName);
                          m_pDatabase->setUserName(sUserName);
                          m_pDatabase->setPassword(sPassword);
                      }
                  
                      QSqlQuery query(*m_pDatabase);
                      bool bCorrect = query.exec("CREATE DATABASE " + sDatabaseName);
                      if (!bCorrect) {
                          qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
                          IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
                          return false;
                      } else {
                          bCorrect = query.exec("USE " + sDatabaseName);
                      }
                  
                      bCorrect = query.exec("CREATE TABLE IF NOT EXISTS Alarms ("
                                            "alarmCode VARCHAR(10) NOT NULL,"
                                            "cameraSN VARCHAR(10),"
                                            "cameraID VARCHAR(2) NOT NULL,"
                                            "presetID VARCHAR(2) NOT NULL,"
                                            "roiID VARCHAR(2) NOT NULL,"
                                            "alarmDate DATE NOT NULL,"
                                            "alarmTime TIME NOT NULL,"
                                            "description VARCHAR(100),"
                                            "data VARCHAR(300),"
                                            "image BYTEA,"
                                            "pathVideo VARCHAR(300),"
                                            "CONSTRAINT pk_alarms PRIMARY KEY (alarmCode, cameraID, presetID, roiID, alarmDate, alarmTime));");
                  
                      if (!bCorrect) {
                          qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
                          IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
                      }
                  
                      bCorrect = query.exec("CREATE TABLE IF NOT EXISTS Data ("
                                            "dataCode VARCHAR(10) NOT NULL,"
                                            "cameraSN VARCHAR(10),"
                                            "cameraID VARCHAR(2) NOT NULL,"
                                            "presetID VARCHAR(2) NOT NULL,"
                                            "roiID VARCHAR(2) NOT NULL,"
                                            "dataDate DATE NOT NULL,"
                                            "dataTime TIME NOT NULL,"
                                            "description VARCHAR(100),"
                                            "data VARCHAR(300),"
                                            "CONSTRAINT pk_data PRIMARY KEY (dataCode, cameraID, presetID, roiID, dataDate, dataTime));");
                  
                      if (!bCorrect) {
                          qDebug() << "[DATABASE ERROR]: " << m_pDatabase->lastError().text();
                          IFDBG (1) { CFileLog::write(QString("[DATABASE ERROR]: " + QString(m_pDatabase->lastError().text())).toStdString().c_str()); }
                      }
                  
                      if (m_pDatabase->open()) {
                          return true;
                      } else {
                          qDebug() << "[DATABASE ERROR]: Database not open." << m_pDatabase->lastError().text();
                          return false;
                      }
                  }
                  
                  J Offline
                  J Offline
                  jsulm
                  Lifetime Qt Champion
                  wrote on 17 Feb 2022, 10:43 last edited by
                  #7

                  @ivanicy You open the database AFTER you use it, how should that work?!

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

                  1 Reply Last reply
                  3
                  • I ivanicy
                    17 Feb 2022, 10:30

                    @JonB I open the database a few lines later, but it can't open it. lastError() is empty:

                    [DATABASE ERROR]: ""
                    
                    J Offline
                    J Offline
                    JonB
                    wrote on 17 Feb 2022, 10:44 last edited by
                    #8

                    @ivanicy said in Create postgreSQL database with Qt:

                    I open the database a few lines later

                    No, I meant before the CREATE DATABASE!
                    Unless I am mistaken, you still must do this to establish a connection with your credentials to do any query.exec() even though I know I know you haven't got a database initially. Unless @Christian-Ehrlicher says otherwise....

                    I 1 Reply Last reply 17 Feb 2022, 10:51
                    1
                    • J JonB
                      17 Feb 2022, 10:44

                      @ivanicy said in Create postgreSQL database with Qt:

                      I open the database a few lines later

                      No, I meant before the CREATE DATABASE!
                      Unless I am mistaken, you still must do this to establish a connection with your credentials to do any query.exec() even though I know I know you haven't got a database initially. Unless @Christian-Ehrlicher says otherwise....

                      I Offline
                      I Offline
                      ivanicy
                      wrote on 17 Feb 2022, 10:51 last edited by
                      #9

                      I tell more details: right now, I create the database with pgAdmin, create the tables with pgAdmin, connect to them with Qt and fill them from Qt. My goal is to create the database and tables from Qt as well, to further automate the process. This code is what has been working for me so far:

                      bool CDatabaseManager::connectToDatabase(const char *sDriverName, QString sServerName, QString sDatabaseName, QString sUserName, QString sPassword)
                      {
                          m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
                      
                          if (m_pDatabase != nullptr) {
                              m_pDatabase->setConnectOptions();
                              m_pDatabase->setHostName(sServerName);
                              m_pDatabase->setDatabaseName(sDatabaseName);
                              m_pDatabase->setUserName(sUserName);
                              m_pDatabase->setPassword(sPassword);
                          }
                      
                          if (m_pDatabase->open()) {
                              return true;
                          } else {
                              qDebug() << "[DATABASE ERROR]: Database not open." << m_pDatabase->lastError().text();
                              return false;
                          }
                      }
                      
                      J J 2 Replies Last reply 17 Feb 2022, 11:41
                      0
                      • I ivanicy
                        17 Feb 2022, 10:51

                        I tell more details: right now, I create the database with pgAdmin, create the tables with pgAdmin, connect to them with Qt and fill them from Qt. My goal is to create the database and tables from Qt as well, to further automate the process. This code is what has been working for me so far:

                        bool CDatabaseManager::connectToDatabase(const char *sDriverName, QString sServerName, QString sDatabaseName, QString sUserName, QString sPassword)
                        {
                            m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
                        
                            if (m_pDatabase != nullptr) {
                                m_pDatabase->setConnectOptions();
                                m_pDatabase->setHostName(sServerName);
                                m_pDatabase->setDatabaseName(sDatabaseName);
                                m_pDatabase->setUserName(sUserName);
                                m_pDatabase->setPassword(sPassword);
                            }
                        
                            if (m_pDatabase->open()) {
                                return true;
                            } else {
                                qDebug() << "[DATABASE ERROR]: Database not open." << m_pDatabase->lastError().text();
                                return false;
                            }
                        }
                        
                        J Offline
                        J Offline
                        jsulm
                        Lifetime Qt Champion
                        wrote on 17 Feb 2022, 11:41 last edited by
                        #10

                        @ivanicy said in Create postgreSQL database with Qt:

                        This code is what has been working for me so far

                        So, create the database and tables now after you open the database

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

                        I 1 Reply Last reply 17 Feb 2022, 13:01
                        3
                        • I ivanicy
                          17 Feb 2022, 10:51

                          I tell more details: right now, I create the database with pgAdmin, create the tables with pgAdmin, connect to them with Qt and fill them from Qt. My goal is to create the database and tables from Qt as well, to further automate the process. This code is what has been working for me so far:

                          bool CDatabaseManager::connectToDatabase(const char *sDriverName, QString sServerName, QString sDatabaseName, QString sUserName, QString sPassword)
                          {
                              m_pDatabase = new QSqlDatabase(QSqlDatabase::addDatabase(sDriverName));        
                          
                              if (m_pDatabase != nullptr) {
                                  m_pDatabase->setConnectOptions();
                                  m_pDatabase->setHostName(sServerName);
                                  m_pDatabase->setDatabaseName(sDatabaseName);
                                  m_pDatabase->setUserName(sUserName);
                                  m_pDatabase->setPassword(sPassword);
                              }
                          
                              if (m_pDatabase->open()) {
                                  return true;
                              } else {
                                  qDebug() << "[DATABASE ERROR]: Database not open." << m_pDatabase->lastError().text();
                                  return false;
                              }
                          }
                          
                          J Offline
                          J Offline
                          JonB
                          wrote on 17 Feb 2022, 13:01 last edited by JonB
                          #11

                          @ivanicy said in Create postgreSQL database with Qt:

                          m_pDatabase->setDatabaseName(sDatabaseName);

                          If your code works, fine. As @jsulm says you are now supposed to add your "create database" code.

                          But it is possible your code will now only work if sDatabaseName already exists --- have you tested when it does not yet exist? At that point it may be that you must not specify a non-existent database name here: you might to leave it blank, or for something like MS SQL Server (which I happen to know about, I don't know about PostgreSQL ) you would specify master if you wanted to connect to create a database.

                          1 Reply Last reply
                          2
                          • J jsulm
                            17 Feb 2022, 11:41

                            @ivanicy said in Create postgreSQL database with Qt:

                            This code is what has been working for me so far

                            So, create the database and tables now after you open the database

                            I Offline
                            I Offline
                            ivanicy
                            wrote on 17 Feb 2022, 13:01 last edited by
                            #12

                            @jsulm Thank you very much! It works perfect now.

                            1 Reply Last reply
                            0

                            1/12

                            17 Feb 2022, 09:34

                            • Login

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