Server SQL中的存儲過程如下:
- CREATE procedure PINSERTPC
- @pcnum int,
- @pcname varchar(50),
- @pctype int,
- @ipaddress varchar(50),
- @port int,
- @pcid int output
- as
- --declare @pcid int
- if exists (select * from COMPUTERTABLE where PcNum = @pcnum)
- set @pcid = -1
- else
- begin
- insert into COMPUTERTABLE (PcNum, PcName, PcType, IpAddress, Port)
- values (@pcnum, @pcname, @pctype, @ipaddress, @port)
- select @pcid = SCOPE_IDENTITY()
- end
- --return @pcid
- GO
根據(jù)網(wǎng)上搜索文章《qt中調(diào)用sql server的存儲過程》內(nèi)容如下:
寫了個存儲過程,準備使用qt調(diào)用,數(shù)據(jù)庫是sqlserver 2000按照參考文檔
調(diào)用是下面這樣的
- QSqlQuery query;
- query.prepare("CALL InsertImgEntity( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
- query.bindValue(0,datano);
- query.bindValue(1,DataCorner);
- query.bindValue(2,DataZD);
- query.bindValue(3,DataCommon);
- query.bindValue(4,ImgCode);
- query.bindValue(5,ImgCodeZ);
- query.bindValue(6,"png");
- query.bindValue(7,pngImage,QSql::Binary);
- query.bindValue(8,"GoldMap Gaoyong Sun");
- query.bindValue(9,QDateTime::currentDateTime ());
但是我在windows下卻無法調(diào)用成功。調(diào)試跟蹤,發(fā)覺我在調(diào)試中存儲過程是通過exec調(diào)用的,故此將代碼修改如下,問題解決,造成這種結(jié)果的原因可能是數(shù)據(jù)庫的不同吧。
- query.prepare("exec InsertImgEntity ?, ?, ?, ?, ?, ?, ?, ?, ?, ?");
- query.bindValue(0,datano);
- query.bindValue(1,DataCorner);
- query.bindValue(2,DataZD);
- query.bindValue(3,DataCommon);
- query.bindValue(4,ImgCode);
- query.bindValue(5,ImgCodeZ);
- query.bindValue(6,"png");
- query.bindValue(7,pngImage,QSql::Binary);
- query.bindValue(8,"GoldMap Gaoyong Sun");
- query.bindValue(9,QDateTime::currentDateTime ());
可是工作需要,存儲過程中要有返回值,或者輸出參數(shù),返回當前插入的ID號。通過測試得到解決方法。以最上方存儲過程為例Qt中代碼如下:
- bool QtSqlServer::SqlInsertPcData(QtPcData* pcData)
- {
- bool bFlag = false;
- QSqlQuery query;
- query.prepare("exec PINSERTPC ?, ?, ?, ?, ?, ? output");
- query.bindValue(0, pcData->GetPcNum());
- query.bindValue(1, pcData->GetPcName());
- query.bindValue(2, pcData->GetPcType());
- query.bindValue(3, pcData->GetIpAddress());
- query.bindValue(4, pcData->GetPort());
- query.bindValue(5, 0, QSql::Out);
- bFlag = query.exec();
- if (bFlag)
- {
- int pcID = query.boundValue(5).toInt();
- if (pcID < 0)
- {
- bFlag = false;
- }
- else
- {
- pcData->SetPcID(pcID);
- bFlag = true;
- }
- }
- else
- {
- QString str = query.lastError().text();
- QMessageBox::critical(0, QObject::tr("Error"),QObject::tr("%1").arg(str));
- }
- return bFlag;
- }
也存在一些未知的疑問……這里的輸出參數(shù)必須設(shè)置在存儲過程的最后一個參數(shù)中返回,而且根據(jù)Server SQL中的要求必須有output的修飾,這樣才可確保成功。
疑問1:如果存儲過程想以返回值的形式返回,使用Qt如何調(diào)用。
疑問2:為何存儲過程的輸出參數(shù)必須設(shè)置才最后一個參數(shù)才可獲取到正確的輸出值,譬如想在第一個參數(shù)中返回,如何解決。
疑問3:有些存儲過程有多個輸出參數(shù),但本人測試Qt只能以一個輸出參數(shù)形式(設(shè)置為最后一個參數(shù))調(diào)用……這事讓我著實頭疼!整的我其他的輸出參數(shù)是在執(zhí)著SQL語句查出來……
歡迎光臨 Chinaunix (http://www.72891.cn/) | Powered by Discuz! X3.2 |