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.
  • ivanicyI Offline
    ivanicyI Offline
    ivanicy
    wrote on 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!!

    JonBJ 1 Reply Last reply
    0
    • ivanicyI ivanicy

      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;
          }
      }
      
      jsulmJ Offline
      jsulmJ Offline
      jsulm
      Lifetime Qt Champion
      wrote on 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

      ivanicyI 1 Reply Last reply
      3
      • ivanicyI ivanicy

        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!!

        JonBJ Offline
        JonBJ Offline
        JonB
        wrote on 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?

        ivanicyI 1 Reply Last reply
        1
        • Christian EhrlicherC Offline
          Christian EhrlicherC Offline
          Christian Ehrlicher
          Lifetime Qt Champion
          wrote on 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
          • JonBJ JonB

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

            ivanicyI Offline
            ivanicyI Offline
            ivanicy
            wrote on last edited by
            #4

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

            [DATABASE ERROR]: ""
            
            Christian EhrlicherC JonBJ 2 Replies Last reply
            0
            • ivanicyI ivanicy

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

              [DATABASE ERROR]: ""
              
              Christian EhrlicherC Offline
              Christian EhrlicherC Offline
              Christian Ehrlicher
              Lifetime Qt Champion
              wrote on 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

              ivanicyI 1 Reply Last reply
              1
              • Christian EhrlicherC Christian Ehrlicher

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

                ivanicyI Offline
                ivanicyI Offline
                ivanicy
                wrote on 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;
                    }
                }
                
                jsulmJ 1 Reply Last reply
                0
                • ivanicyI ivanicy

                  @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;
                      }
                  }
                  
                  jsulmJ Offline
                  jsulmJ Offline
                  jsulm
                  Lifetime Qt Champion
                  wrote on 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
                  • ivanicyI ivanicy

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

                    [DATABASE ERROR]: ""
                    
                    JonBJ Offline
                    JonBJ Offline
                    JonB
                    wrote on 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....

                    ivanicyI 1 Reply Last reply
                    1
                    • JonBJ JonB

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

                      ivanicyI Offline
                      ivanicyI Offline
                      ivanicy
                      wrote on 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;
                          }
                      }
                      
                      jsulmJ JonBJ 2 Replies Last reply
                      0
                      • ivanicyI ivanicy

                        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;
                            }
                        }
                        
                        jsulmJ Offline
                        jsulmJ Offline
                        jsulm
                        Lifetime Qt Champion
                        wrote on 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

                        ivanicyI 1 Reply Last reply
                        3
                        • ivanicyI ivanicy

                          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;
                              }
                          }
                          
                          JonBJ Offline
                          JonBJ Offline
                          JonB
                          wrote on 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
                          • jsulmJ jsulm

                            @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

                            ivanicyI Offline
                            ivanicyI Offline
                            ivanicy
                            wrote on last edited by
                            #12

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

                            1 Reply Last reply
                            0

                            • Login

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