0

I am currently working with QT creator and PostgreSQL.

#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QString>
#include <QDebug>
#include <QtSql>

static QSqlDatabase DB = QSqlDatabase::addDatabase("QPSQL");

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    DB.setHostName("db.fe.up.pt");
    DB.setDatabaseName("****");
    DB.setUserName("*****");
    DB.setPassword("****");



    if (DB.open())
    {
        qDebug() << "Connected!";
        QSqlQuery query2;
        if(query2.exec("SET search_path TO INFI")){
            qDebug() << "Schema OK";
        }
    }
    else
    {
        qDebug() << "Failed to connect.";
        //ui->LogOk->setText("You not are connected to VPN!! ");
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}


void MainWindow::on_orders_clicked()
{

   QSqlQuery query;
   QSqlQueryModel *model = new QSqlQueryModel;

   if(query.exec("SELECT * from INFI.orders")){
       qDebug()<< "TOP";
   }
   else{
       qDebug()<< "Failed";
   }
   model->setQuery(std::move(query));

}


I am trying to run this piece of code, and when I execute my app my connection with the DB are ok. But I dont know why I cant execute this query when I press the button, my qDebug always return me "failed", what I am doing wrong?? This is the tables and the schema I am working. I want to select all the items of my orders table, this table is inside INFI schema.

DB

thaidy_04
  • 3
  • 3
  • You should use `QSqlQuery::lastError()` (for instance: `qDebug() << query.lastError().text();`) to find what the error was, instead of just printing "failed". Also, you are not supposed to keep a global variable with a `QSqlDatabase` constantly open as I explained [here](https://stackoverflow.com/a/7689551/894321). – alexisdm May 22 '22 at 00:57
  • Your screenshot does not show a table 'orders' in schema 'INFI' but in schema 'up201806281' – chehrlic May 22 '22 at 11:06
  • The tables on the right side belongs to INFI schema – thaidy_04 May 22 '22 at 13:16

0 Answers0