1. 程式人生 > 其它 >ocilib呼叫儲存過程

ocilib呼叫儲存過程

技術標籤:ocilib開源庫

1、輸出引數為一個查詢遊標:

(1)建立儲存過程:

CREATE OR REPLACE PROCEDURE GETCURSOR(MYCURSOR OUT SYS_REFCURSOR)
AS
BEGIN
OPEN MYCURSOR FOR SELECT * FROM dept;
END;

(2)編寫程式呼叫儲存過程:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "ocilib.hpp"
#pragma comment(lib, "ociliba.lib")
using namespace ocilib;

//測試儲存過程
int _tmain(int argc, _TCHAR* argv[])
{
	try
	{
		Environment::Initialize(Environment::Default | Environment::Threaded);
		Environment::EnableWarnings(true);
		Connection con("orcl", "scott", "tiger");
		Statement st(con);
		Statement stBind(con);

		st.Prepare("begin GETCURSOR(:cursor); end;");
		st.Bind(":cursor", stBind, BindInfo::Out);
		st.ExecutePrepared();

		Resultset rs = stBind.GetResultset();
		while (rs++)
		{
			std::cout << rs.Get<int>(1) << " : " << rs.Get<ostring>(2) << " : " << rs.Get<ostring>(3) << std::endl;
		}
		
		if (con) con.Close();
	}
	catch (std::exception &ex)
	{
		std::cout << ex.what() << std::endl;
	}
	Environment::Cleanup();
	system("pause");
	return 0;
}

(3)結果:

2、呼叫一個帶有輸入、輸出引數的儲存過程:

(1)、建立:

CREATE OR REPLACE PROCEDURE GET_DNAME_BY_DEPTNO(ndeptno in NUMBER,strname out varchar2)
AS
BEGIN
select DNAME into strname from DEPT WHERE DEPTNO = ndeptno;
exception
    when no_data_found then
    dbms_output.put_line('1001001');
END GET_DNAME_BY_DEPTNO;

(2)呼叫:

#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "ocilib.hpp"
#pragma comment(lib, "ociliba.lib")
using namespace ocilib;

int _tmain(int argc, _TCHAR* argv[])
{
	try
	{
		Environment::Initialize(Environment::Default | Environment::Threaded);
		Environment::EnableWarnings(true);
		Connection con("orcl", "scott", "tiger");
		Statement st(con);
		
		int no = 70;
		ostring strname;
		st.Prepare("begin GET_DNAME_BY_DEPTNO(:no, :name); end;");
		st.Bind(":no", no, BindInfo::In);
		st.Bind(":name", strname, 260, BindInfo::Out);
		st.ExecutePrepared();

		std::cout << strname << std::endl;

		if (con) con.Close();
	}
	catch (std::exception &ex)
	{
		std::cout << ex.what() << std::endl;
	}
	Environment::Cleanup();
	system("pause");
	return 0;
}