您的位置:首页 > 编程语言 > C语言/C++

C++通过ADO调用存储过程

2013-10-21 10:35 435 查看
很久以前就在网上找了一些关于用C++调用数据库存储过程的文章,并用到了自己的项目中。网上的文章都是要定义_CommandPtr和_ParameterPtr类型的智能指针对象,然后用pCmd->Excute(...)的方法来执行。这样做也没什么不好,就是麻烦了点。这两天突然来了灵感,想到一个更简单的方法:

#include <iostream>
#include <Windows.h>
using namespace std;

#import "C:\Program Files\Common Files\System\ado\msado15.dll" no_namespace rename ("EOF","rsEOF")

int main()
{
_wsetlocale(NULL,L"chs");
CoInitialize(NULL);
_ConnectionPtr pConn(__uuidof(Connection));
_RecordsetPtr pRst(__uuidof(Recordset));

pConn->ConnectionString = L"provider=msdasql;driver={sql server};server=xxx.xxx.xxx.xxx;uid=xxx;pwd=xxxxx;database=xxxxx";
pConn->Open("","","",adConnectUnspecified);

//这一句是执行存储过程的关键
//GetSchemas2便是存储过程的名称
//后面括号中的(2,\"zrs\")便是其参数列表
//注意Open方法的最后一个参数是adCmdStoredProc,而我们平常常用的是adCmdText
pRst->Open(L"GetSchemas2(2,\"zrs\")",_variant_t((IDispatch*)pConn),adOpenKeyset,adLockOptimistic,adCmdStoredProc);

if(1 == pRst->State)
{
long n = pRst->GetRecordCount();
wcout<<L"记录行数:"<<n<<endl;
if(n>0)
{
pRst->MoveFirst();
while(!pRst->rsEOF)
{
int ID = pRst->GetCollect(L"ID");
wstring sname = (_bstr_t)pRst->GetCollect(L"SchemaName");
int DID = pRst->GetCollect(L"DesignerID");
wstring name = (_bstr_t)pRst->GetCollect(L"DesignerTrueName");
int PIR = pRst->GetCollect(L"Prior");
wcout<<ID<<L"    "<<sname.c_str()<<L"   "<<DID<<L"   "<<name.c_str()<<L"   "<<PIR<<endl;
pRst->MoveNext();
}
}
pRst->Close();
}

pConn->Close();
pRst.Release();
pConn.Release();
CoUninitialize();
system("pause");
return -1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++ ado 存储过程