Declaration of class data members as host variables in C++ embedded SQL applications
The following example illustrates the method to use:
class STAFF
{
private:
EXEC SQL BEGIN DECLARE SECTION;
char staff_name[20];
short int staff_id;
double staff_salary;
EXEC SQL END DECLARE SECTION;
short staff_in_db;
.
.
};
Data members are only directly accessible in SQL statements through
the implicit this pointer provided by the C++ compiler in class
member functions. You cannot explicitly qualify an object instance
(such as SELECT name INTO :my_obj.staff_name ...)
in an SQL statement.
If you directly refer to class data members in SQL statements, the database manager resolves the reference using the this pointer. For this reason, you should leave the optimization level precompile option (OPTLEVEL) at the default setting of 0 (no optimization).
The following example shows how you might directly use class data members which you have declared as host variables in an SQL statement.
class STAFF
{
.
.
.
public:
.
.
.
short int hire( void )
{
EXEC SQL INSERT INTO staff ( name,id,salary )
VALUES ( :staff_name, :staff_id, :staff_salary );
staff_in_db = (sqlca.sqlcode == 0);
return sqlca.sqlcode;
}
};
In this example, class data members staff_name, staff_id,
and staff_salary are used directly in the INSERT
statement. Because they have been declared as host variables (see
the first example in this section), they are implicitly qualified
to the current object with the this pointer. In SQL statements,
you can also refer to data members that are not accessible through
the this pointer. You do this by referring to them indirectly
using pointer or reference host variables.
The following example shows a new method, asWellPaidAs that takes a second object, otherGuy. This method references its members indirectly through a local pointer or reference host variable, as you cannot reference its members directly within the SQL statement.
short int STAFF::asWellPaidAs( STAFF otherGuy )
{
EXEC SQL BEGIN DECLARE SECTION;
short &otherID = otherGuy.staff_id
double otherSalary;
EXEC SQL END DECLARE SECTION;
EXEC SQL SELECT SALARY INTO :otherSalary
FROM STAFF WHERE id = :otherID;
if( sqlca.sqlcode == 0 )
return staff_salary >= otherSalary;
else
return 0;
}