qry1.prepare("insert into table_1(first_name, last_name) values (:first_name, :last_name)");
qry2.prepare("insert into table_2(import, name1, name2) values (last_insert_rowid(), :name1, :name2)" );
if (db.transaction()) {
bool success = false;
qry1.bindValue(":first_name", ui->lineEdit1->text());
qry1.bindValue(":last_name", ui->lineEdit2->text());
if (qry1.exec()) {
qry2.bindValue(":name1", ui->lineEdit3->text());
qry2.bindValue(":name2", ui->lineEdit4->text());
if (qry2.exec()) {
success = true;
}
}
if (success) {
db.commit();
}
else {
// SQL died for some reason
db.rollback();
}
}
else {
// error could not start transaction
}
QSqlDatabase db = QSqlDatabase::database(); // I am assuming default database connection
QSqlQuery qry1;
qry1.prepare("insert into table_1(first_name, last_name) values (:first_name, :last_name)");
QSqlQuery qry2;
qry2.prepare("insert into table_2(import, name1, name2) values (last_insert_rowid(), :name1, :name2)" );
if (db.transaction()) {
bool success = false;
qry1.bindValue(":first_name", ui->lineEdit1->text());
qry1.bindValue(":last_name", ui->lineEdit2->text());
if (qry1.exec()) {
qry2.bindValue(":name1", ui->lineEdit3->text());
qry2.bindValue(":name2", ui->lineEdit4->text());
if (qry2.exec()) {
success = true;
}
}
if (success) {
db.commit();
}
else {
// SQL died for some reason
db.rollback();
}
}
else {
// error could not start transaction
}
To copy to clipboard, switch view to plain text mode
Bookmarks