QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL"); db.setHostName("localhost"); db.setDatabaseName("mydb"); db.setUserName("root"); db.setPassword("password"); if (db.open()) { QSqlQuery query("INSERT INTO mytable VALUES (1, 'example')"); if (query.exec()) { db.commit(); } }
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("mydb.sqlite"); if (db.open()) { QSqlQuery query(db); db.transaction(); query.prepare("INSERT INTO mytable VALUES (?, ?)"); query.bindValue(0, 1); query.bindValue(1, "example"); if (query.exec()) { db.commit(); } }In this example, we connect to a SQLite database and insert a record into a table using a prepared statement. We start a transaction using db.transaction() and commit it using db.commit() after executing the query. Package Library: Qt (QtSql module)