Database connection
Create a nt project, as explained in previous articles. The new thing to do is add the SnL module in the project (.pro) fiOH, DV IoOOowV:
QT
+= core gui sql
This will add the nt SnL classes to your application. To understand how to connect with the database, let’s right away HxDPLQH VoPH VDPSOH FoGH: #include <QtGui/QApplication> #include “dialog.h” #include<QtGui> #include <QtCore> #include <QtSql> int main(int argc, char *argv[]) { QApplication a(argc, argv); Dialog w; w.show();
} QSqlDatabase db = QSqlDatabase::addDatabase(“QMYSQL”); db.setHostName(“localhost”); db.setDatabaseName(“osslabs”); db.setUserName(“oss”); db.setPassword(“oss123”); if (!db.open()) {
qDebug() << db.lastError(); } qDebug() << “Database opened successfully”; return a.exec();
The class that deals with the database connection is QsqlDatabase; you need to provide a database driver name to the constructor — ‘nMYSnL’, in our case. kext, set the host name where the MySnL server is running. In this case, it’s localhost. Then set the database name, username and password. kow open the database. If it’s not successfully opened, you can get the error from the lastError() member function.