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();
}