Connection Database in Qt creator

13,105

this question is very shallow, but i will try to provide some ressources as this shows up pretty on top on many searches.

First of all, you will have to compile the MYSQL driver for the QtCreator for your operating system.

For Windows, check

QT MySql connectivity using Windows XP, Qt Creator 4.5.2(windows 32 bit)

Instructions for MacOS (and probably Linux) can be found here

http://www.qtcentre.org/threads/45296-QSqlDatabase-QMYSQL-driver-not-loaded

Once your qt install includes the mysql driver, you can use the database with the (QSqlDatabase)(developer.qt.nokia.com/doc/qsqldatabase.html) class. Copying from here:

QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("mysql");
db.setUserName("root");
db.setPassword("rootPW");
if (!db.open()) qDebug() << "Failed to connect to root mysql admin";

After that, you can use QSqlQuery to work with the database handle, e.g.

QSqlQuery query("SELECT * FROM mysql",db);

and print the results like

while (query.next()) {
  qDebug() << "first column:" << query.value(0).toString();
}

Code is not tested, but the Qt Documentation should clarify all details

Share:
13,105
Boudour
Author by

Boudour

Updated on June 04, 2022

Comments

  • Boudour
    Boudour about 2 years

    How do I connect to the MySQL database using QT4 and Qt Creator? I have no idea how I should proceed, if anyone can help me please..