How to get a column from an sql table after running query

Viewed 796

i have recently been writing a program for a simple login window as a part of a project i have been working on. I have an SQL database structured as follows:

User:    
 __________________________________________
| id | name | username | password | status |
| ___+______+__________+__________+________|
| 1  | niko | ******** | ******** | admin  |
| 2  | andy | ******** | ******** | user   |
 ------------------------------------------

and a few more columns that go on like that. I have prepared an sql query in c++ in QTcreator as follows:

qry.prepare("SELECT name FROM Database.User WHERE username = :username AND password = :password")

which ideally is supposed to get either niko or andy or any other name for a given password and username. The only problem is i am not sure how to work with it. I have read the QT documentation multiple times and haven't found any way of obtaining the name as a string. I have tried to print it using:

qDebug<<qry.result()

however that only returns "0x5561eb32d240" I am not sure on what this is? Qt hasn't documented result() and the only thing i know about the return of result is that it is a const QSql type.

Any ideas on how may i be able to return name as a string for later use?

1 Answers

This is the example with qsqlite. It have to be work.

QSqlDatabase data_base;
data_base = QSqlDatabase::addDatabase("QSQLITE", id);
data_base.setDatabaseName(data_base_path);

if (data_base.open())

{
    QString query = "SELECT name FROM Database.User WHERE username = :username AND password = :password";
    QSqlQuery SqlQuery = QSqlQuery( data_base );
    SqlQuery.exec( query );

    while (SqlQuery.next())
    {
        int field_idx   = SqlQuery.record().indexOf("name");
        QString name = SqlQuery.record().value( field_idx ).toString();
        qDebug() << name;
    };
}
Related