Qt數據庫查詢之事務操作


  在做借書系統的時候,用到了事務操作,不會使用qt中事務操作怎么寫,查了一些博客帖子,並不起作用,后來發現,在進行事務成功判斷時,出現問題,正確代碼如下

 if(QSqlDatabase::database().transaction()){
                    bool res1,res2;
                    query.prepare("update booklist set borrowNum=?,restNum=? where bookId=?");
                    query.bindValue(0,++borrownum);
                    query.bindValue(1,--restnum);
                    query.bindValue(2,bookId);
                    res1=query.exec();
                    //qDebug()<<"insert "<<res1;

                    query.prepare("insert into recordlist(bookId,bookName,borrowPeople,borrowTime,backTime,\
                                  backState) values(?,?,?,?,?,?)");
                    query.bindValue(0,bookId);
                    query.bindValue(1,bookName);
                    query.bindValue(2,userName);
                    query.bindValue(3,borrowTime);
                    query.bindValue(4,"");
                    query.bindValue(5,0);
                    res2=query.exec();
                     //qDebug()<<query.lastError();

                    //qDebug()<<"insert "<<res2;
                    if(res1&&res2){
                        if(!QSqlDatabase::database().commit()){
                            QMessageBox::critical(this,"Error","操作失敗,將要回滾");
                            if(!QSqlDatabase::database().rollback()){
                                QMessageBox::critical(this,"Error","回滾失敗");
                            }
                        }else{
                            doShowBackResult();
                            //qDebug()<<"show ";
                        }
                    }else{
                        qDebug()<<query.lastError();
                        QMessageBox::critical(this,"Error","操作失敗,將要回滾");
                        if(!QSqlDatabase::database().rollback()){
                            QMessageBox::critical(this,"Error","回滾失敗");
                            qDebug()<<QSqlDatabase::database().lastError();
                        }
                    }

                }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM