Qt调用Server SQL中的存储过程

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的修饰,这样才可确保成功。

猜你喜欢

转载自blog.csdn.net/lengyuezuixue/article/details/80853226