您的位置:首页 > 编程语言 > Qt开发

Qt调用Server SQL中的存储过程

2017-01-04 23:52 393 查看
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


根据网上搜索文章《qt中调用sql server的存储过程》内容如下:

写了个存储过程,准备使用qt调用,数据库是sqlserver 2000按照参考文档
调用是下面这样的


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下却无法调用成功。调试跟踪,发觉我在调试中存储过程是通过exec调用的,故此将代码修改如下,问题解决,造成这种结果的原因可能是数据库的不同吧。


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 ());



可是工作需要,存储过程中要有返回值,或者输出参数,返回当前插入的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;
}


也存在一些未知的疑问……这里的输出参数必须设置在存储过程的最后一个参数中返回,而且根据Server SQL中的要求必须有output的修饰,这样才可确保成功。

疑问1:如果存储过程想以返回值的形式返回,使用Qt如何调用。
疑问2:为何存储过程的输出参数必须设置才最后一个参数才可获取到正确的输出值,譬如想在第一个参数中返回,如何解决。
疑问3:有些存储过程有多个输出参数,但本人测试Qt只能以一个输出参数形式(设置为最后一个参数)调用……这事让我着实头疼!整的我其他的输出参数是在执着SQL语句查出来……

最近貌似挺贪玩....要收敛收敛了!嘿嘿!上述问题如果有人可以解答,小的十分感激,彼此交流,相互学习!
http://cool.worm.blog.163.com/blog/static/6433900620091018103220702/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: