#includeQSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("myDatabase.sqlite"); if (!db.open()) { qDebug() << "Failed to connect to database"; return; } QString queryString = "SELECT * FROM myTable"; QSqlQuery query(queryString, db); while (query.next()) { QString name = query.value("name").toString(); int age = query.value("age").toInt(); qDebug() << name << age; } db.close();
#includeIn this example, we perform a prepared statement using a SQL string with named parameters. We then bind the values to the named parameters using the bindValue method of the QSqlQuery object. The query is then executed and the result is looped over and printed to the console. Package Library: QtSqlQSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("myDatabase"); db.setUserName("myUserName"); db.setPassword("myPassword"); if (!db.open()) { qDebug() << "Failed to connect to database"; return; } QString queryString = "SELECT * FROM myTable WHERE name = :name AND age = :age"; QSqlQuery query(db); query.prepare(queryString); query.bindValue(":name", "John Doe"); query.bindValue(":age", 30); query.exec(); while (query.next()) { QString name = query.value("name").toString(); int age = query.value("age").toInt(); qDebug() << name << age; } db.close();