Class Sql - Program Example
Class Sql allows to execute any SQL statement. Bind data and
fetch (in case of select statement) is loaded using overloaded
operators >> and <<. C++ program below shows use of Sql
class, where select and update statements are processed using on Sql object.
// sql_example.cc
#include <orac_lib.h>
int main()
{
int prod_id;
double price;
TStr id_str(10),
name_str(30), price_str(30);
Connect c;
try {
Database d =
c.OpenDatabase("demo", "demo");
Sql st =
d.GetSql("select * from products where prod_id = :1");
st << id_str << name_str
<< price_str; // fetch into strings
st >> 100001;
while (st.Execute())
{
st << id_str <<
name_str << price_str;
st << id_str <<
":" << name_str << ":" <<
price_str << endl;
}
st = " update products";
st += "set prod_desc = :1";
st += "where prod_id = :2";
st >> "updated
description" >> 100001;
st.Execute();
st = "select * from products";
st << prod_id << name_str
<< price; // fetch into proper data types
while(st.Execute())
{
<< prod_id <<
name_str << price;
cout << id_str
<< ":" << name_str << ":"
<< price_str << endl;
}
}
catch (OException& e) {
cerr << e.Show() << endl;
}
catch (...) {
cerr << " Error ..."
<< endl;
}
return 0;
}
C++ program below demostrates use of Sql class to process stored
procedure and stored function.
// sql_example_proc.cc
#include <orac_lib.h>
int main()
{
int type, id = 100001;
TStr desc(30); //
set size to 30
Connect c;
try {
Database d =
c.OpenDatabase("demo", "demo");
Sql st = d.GetSql("begin\n");
st += " p_get_description(:1, :2);";
st += "end\n;";
st >> id >> desc; //
define bind variables
st.Execute())
st << id << desc; //
reload variables
cout << id << ":"
<< desc << endl;
st = "begin\n";
st += " :0 := f_get_description(:1, :2);";
st += "end\n;";
st >> type >> id >>
desc; // define bind variables
st.Execute();
st << type << id <<
desc; // reload variables
cout << type << id <<
":" << desc << endl;
}
catch (OException& e) {
cerr << e.Show() << endl;
}
catch (...) {
cerr << "Error ..."
<< endl;
}
return 0;
}