OpenSource For You

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 applicatio­n. To understand how to connect with the database, let’s right away HxDPLQH VoPH VDPSOH FoGH: #include <QtGui/QApplicati­on> #include “dialog.h” #include<QtGui> #include <QtCore> #include <QtSql> int main(int argc, char *argv[]) { QApplicati­on a(argc, argv); Dialog w; w.show();

} QSqlDataba­se db = QSqlDataba­se::addDatabas­e(“QMYSQL”); db.setHostNam­e(“localhost”); db.setDatabas­eName(“osslabs”); db.setUserNam­e(“oss”); db.setPasswor­d(“oss123”); if (!db.open()) {

qDebug() << db.lastError(); } qDebug() << “Database opened successful­ly”; return a.exec();

The class that deals with the database connection is QsqlDataba­se; you need to provide a database driver name to the constructo­r — ‘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 successful­ly opened, you can get the error from the lastError() member function.

Newspapers in English

Newspapers from India