Qt SQL on Qt Basic connection and query

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

The QSqlDatabase class provides an interface for accessing a database through a connection. An instance of QSqlDatabase represents the connection. The connection provides access to the database via one of the supported database drivers. Make sure to Add

QT += SQL 

in the .pro file. Assume an SQL DB named TestDB with a countryTable that contines the next column:

| country |
-----------
| USA     |

In order to query and get sql data from TestDB:

#include <QtGui>
#include <QtSql>
 
int main(int argc, char *argv[])
{
    QCoreApplication app(argc, argv);

    QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); // Will use the driver referred to by "QPSQL" (PostgreSQL Driver) 
    db.setHostName("TestHost");
    db.setDatabaseName("TestDB");
    db.setUserName("Foo");
    db.setPassword("FooPass");
    
    bool ok = db.open();
    if(ok)
    {
        QSqlQuery query("SELECT country FROM countryTable");
        while (query.next())
        {
          QString country = query.value(0).toString();
          qWarning() << country; // Prints "USA"
        }
    }

    return app.exec();
}


Got any Qt Question?