QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("my_database"); db.setUserName("my_username"); db.setPassword("my_password"); if (!db.open()) { qDebug() << "Error: Unable to connect to database."; }
QSqlQuery query; query.exec("SELECT * FROM my_table"); while (query.next()) { QString name = query.value("name").toString(); int age = query.value("age").toInt(); qDebug() << "Name: " << name << ", Age: " << age; }In this example, we create a `QSqlQuery` object and execute a SELECT query on a table named `my_table`. We then iterate through the results and retrieve the values of the `name` and `age` columns using the `value()` method. Finally, we output the results using `qDebug()`. Overall, QSqlDatabase is a useful class for managing database connections and performing SQL queries in C++.