您的位置:首页 > 数据库 > Oracle

调用带参数的存储过程,并返回结果集--oracle

2010-11-23 00:29 591 查看
调用插入数据的存储过程:

// 调用存储过程来插入一条记录
BOOL CDBTestAppDlg::InsertRecord()
{
CAdoParameter param1, param2, param3;
CAdoCommand comm;
if(ConnTODB())
{
comm.SetConnection(m_pConnection);

param1.SetSize(20);
param1.SetName("C_Name");
param1.SetDirection(adParamInput);
param1.SetType(adVarChar);				// varchar2
param1.SetValue((CString)"hello113");	// 这里必须用类型转换,默认的参数类型为bool,所以转换会出错
comm.Append(param1.GetParameter());

param2.SetName("C_Age");
param2.SetDirection(adParamInput);
param2.SetType(adInteger);				// Integer
param2.SetValue(21);
comm.Append(param2.GetParameter());

param3.SetName("C_ExeTime");
param3.SetDirection(adParamInput);
param3.SetType(adVarChar);				// varchar2
param3.SetValue((CString)"2010-1-10");
comm.Append(param3.GetParameter());

comm.SetCommandText("Proc_Insert");
comm.SetCommandType(adCmdStoredProc);

try
{
comm.Execute();
MessageBox("Procedure execute success!", "执行成功", MB_OK | MB_ICONINFORMATION);
return TRUE;
}
catch (CException* e)
{
char errorMessage[256];
e->GetErrorMessage(errorMessage, 255);
MessageBox(errorMessage);
}
}
return FALSE;
}


其中连数据库的函数为:


为了返回结果集,首先要建立一个包,再建立一个包体,代码如下:

CREATE OR REPLACE Package pkg_GetResult
as
Type myResult is REF CURSOR;                           -- 定义返回值类型
Procedure getResult(age number, pResult out myResult);
-- 声明pResult为输出的结果集变量
end pkg_GetResult;
/
CREATE OR REPLACE Package Body pkg_GetResult
as
Procedure getResult(age number, pResult out myResult)
IS
sqlstr varchar2(200);
begin
if age = 0 then
open pResult for Select C_ID, C_Name, C_Age, C_InTime, C_Salary, C_ExeTime from T_Test;
else
sqlstr := 'Select C_ID, C_Name, C_Age, C_InTime, C_Salary, C_ExeTime from T_Test where C_Age=:w_age';
open pResult for sqlstr using age;
end if;
end getResult;
end pkg_GetResult;


在vc中调用这个包中的存储过程,调用方法:包名.存储过程名(参数1, 参数2, ...):

BOOL CDBTestAppDlg::GetResult(CString ProcName, int age)
{
if(ConnTODB())
{
try
{
CString sql;
sql.Format("{call %s(%d)}", ProcName, age);	// 调用包中的存储过程:packageName.procedureName(参数1,参数2...)
TRACE(sql + "\n");
m_pRecordSet.Open(sql, adCmdText, adOpenStatic, adLockReadOnly);
TRACE("Procedure execute success!");

while(!m_pRecordSet.IsEOF())
{
CString name, age;
m_pRecordSet.GetCollect("C_Name", name);

m_pRecordSet.GetCollect("C_Age", age);

MessageBox("name = " + name + ", age = " + age);
//	TRACE("name = " + name + ", age = " + age);

m_pRecordSet.MoveNext();
}

return TRUE;
}
catch (CException* e)
{
char errorMessage[256];
e->GetErrorMessage(errorMessage, 255);
MessageBox(errorMessage);
return FALSE;
}
}
return FALSE;
}


通过CRecordSet的Open()方法可以返回结果集,再进行遍历。这里用到了一些自定义的函数,因为相对简单,所以未给出。这里的调用是adCmdText,而不是adCmdStoredProc
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: