1

I have connected to PostgreSQL database successfully but I can not seem to query it I have tried several queries but keep facing with this error.

Connection Successful
QSqlError("42601", "QPSQL: Unable to create query", "ERROR:  syntax error at 
end of input\nLINE 1: EXECUTE \n                ^\n(42601)")

My code

void MainWindow::connection()
{
    QSqlDatabase db;
    db = QSqlDatabase::addDatabase("QPSQL");
    db.setHostName("localhost");
    db.setDatabaseName("postgres");
    db.setUserName("postgres");
    db.setPassword("xxx");
    db.setPort(5433);
    if (db.open())
        qDebug() << "Connection Successful";
    else
        qDebug() << "Connection Failed!";
}

void MainWindow::query()
{
    QSqlQuery query("select * from company");
    if( !query.exec())
            qDebug() << query.lastError();
    else
    {
        while(query.next())
        {
            qDebug() << query.value(0).toString();
            ui->label_2->setText(query.value(0).toString());
        }
    }
}

can anyone please enlighten me

1
  • Did you look into log files on the PostGreSQL server? Commented Sep 29, 2017 at 9:45

1 Answer 1

2

You are using the Qt functions incorrectly.

QSqlQuery query("select * from company"); directly executes the query, no need to call exec(). Calling exec() runs a previously prepared query but you have not prepared any which causes the error.

You might want to consult Executing SQL Statements and SqlQuery reference

EDIT: a construct like this works for me:

QSqlQuery query("select * from company");
QSqlError error = query.lastError();
if (error.type() == QSqlError::NoError) {
    while(query.next())
    {
        qDebug() << query.value(0).toString();
        ui->label_2->setText(query.value(0).toString());
    }
}
else {
    qDebug() << error.text();
}
Sign up to request clarification or add additional context in comments.

3 Comments

I have just tried this there's no error but it's not executing the query now.
Are you certain you are running the query on the right database? You specified postgres as the name of the database. When you change your code then also edit your question to reflect your changes so we know what you are doing.
Checking for error's after executing the query is always a good idea. See my example code in my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.