|
|
|
When you start the project with Oracle Class Library you should include ocl.h header from ocl/include directory to your project and link it with ocl.lib from ocl/lib directory.
#include "ocl.h"
Before using OCL classes you can include whole ocl namespace
using namespace ocl;
The first object which you must obligatory create is OraConnection object that opens and controls connection to Oracle server. Use its member functions setUsername, setPassword, setServer to set login information. And establish connection with connect function.
OraConnection connection;
connection.setUsername("scott");
connection.setPassword("tiger");
connection.setServer("ora");
connection.open();
You can execute any SQL or PL/SQL statement using OraCommand object. Before you need link it to OraConnection object by setConnection member function. Set text of SQL by setCommandText member function and execute it by execute method.
OraCommand cmd;
cmd.setConnection(connection);
cmd.setCommandText("INSERT INTO Emp (EmpNo) VALUES (8315)");
cmd.execute();
Use param function to access to input and output parameters and member functions of OraParam to write and read their values.
cmd.setCommandText("INSERT INTO Dept (DeptNo, DName) VALUES (:DeptNo, :DName)");
cmd.param("DeptNo").setInt(70);
cmd.param("DName").setString("Research");
To execute SQL that returns rows use OraQuery object. Call setCommandText function to set text of SQL statement and open to retrieve records from database.
OraQuery query;
query.setConnection(connection);
query.setCommandText("SELECT * FROM Dept");
query.open();
To navigate through records use next, prev, first, last and move member functions. Check current record position by isEOF, isBOF, recordNo member functions. To access to fields use field function.
while (!query.isEOF()) {
cout << "DName: " << query.field("DName").getString() << endl;
query.next();
}
Example
#include <iostream>
#include "ocl.h"
using namespace std;
using namespace ocl;
int main() {
OraConnection connection;
OraCommand cmd(connection);
OraQuery query(connection);
int deptNo;
connection.open("scott/tiger@ora");
cmd.setSQL("begin SELECT Max(DeptNo) INTO :MaxNo FROM Dept; end;");
cmd["MaxNo"].setDataType(dtInt);
cmd.execute();
deptNo = cmd["MaxNo"].getInt();
cmd.setCommandText(
"INSERT INTO Dept(DeptNo, DName) VALUES (:DeptNo, :DName)");
cmd["DeptNo"].setInt(deptNo + 1);
cmd["DName"].setString("Research");
cmd.execute();
query.setCommandText("SELECT * FROM Dept");
query.open();
while (!query.isEOF()) {
cout << "DName: " << query.field("DName").getString() << endl;
query.next();
}
query.close();
connection.close();
return 0;
}
See Also
OraConnection, OraCommand, OraQuery
OCL | Using OCL | Index