Contents
These classes encapsulate the complicated DB2 CLI APIs, so that developers
can access DB2 database in a simple, ADO style way.
CSqlDatabase |
Represents a connection to a database |
CSqlCommand |
Defines a specific command (SQL statement) |
CSqlRecordset |
Represents a set of records selected from table(s) or the results of an
executed command |
CSqlParameter |
Represents a parameter or argument associated with a SQL statement or stored
procedure |
CSqlField |
Represents a column of data in a recordset |
CSqlLocator |
Manipulates a locator to access large object data |
CSqlErrorInfo |
Provides information associated with a DB2
error |
These classes can be used in either Windows or AIX environment. The compilers
use predefined macro to identify themselves. for MSVC it's
_MSC_VER
; for xlC it's __xlC__
.
In the current version, I use STL (Standard Template Library) to manipulate
string and collections. Unfortunately the current version of AIX C++ compiler
(xlC) doesn't support STL. So I used STLport, a free, multiplatform ANSI STL
library.
STLport can be downloaded from: http://www.stlport.org/
To use DB2 Access Classes in your program, you need to add the 2 .cpp files
and 4 .h files in your project, and include sqldb2.h in your source
file.
While you compile sqldb2.cpp or sqldata.cpp with VC++, you
might meet the error: fatal error C1010: unexpected end of file while looking
for precompiled header directive. To solve this problem, you should include the
precompiled header file (usually it is stdafx.h) in sqldb2.cpp
and sqldata.cpp.
The application must at first call the global function
CSqlDatabase::Initialize
to initialize the DB2 CLI environment
before accessing DB2, and call CSqlDatabase::Uninitialize
to
release the environment afterwards.
Use CSqlDatabase
class to connect to a database; use
CSqlCommand
class to execute a SQL statement.
#include <stdio.h>
#include "sqldb2.h"
void main()
{
CSqlDatabase::Initialize();
CSqlDatabase db;
db.Connect("mydb", "user_name", "password");
CSqlCommand cmd;
cmd.Create(&db, CSqlCommand::execDirect);
cmd.SetCommand("CREATE TABLE Employee (Name VARCHAR(20), "
"Sex CHAR(1), EmployDate DATE, Age INT)");
cmd.Execute();
cmd.Reset();
cmd.SetCommand("INSERT INTO Employee VALUES ('John', 'M', "
"'2000-1-1', 25)");
cmd.Execute();
db.Close();
CSqlDatabase::Uninitialize();
}
Parameterized commands are more efficient if you need to execute a command
repeatedly while only a few parameters need be to changed.
CSqlCommand cmd;
cmd.Create(&db);
cmd.SetCommand("INSERT INTO Employee VALUES (?, ?, ?, ?)");
CSqlParameter param;
param.CreateParameter(SQL_CHAR, SQL_PARAM_INPUT, 20);
cmd.Parameters().Add(param);
param.CreateParameter(SQL_CHAR, SQL_PARAM_INPUT, 1);
cmd.Parameters().Add(param);
param.CreateParameter(SQL_TYPE_DATE, SQL_PARAM_INPUT);
cmd.Parameters().Add(param);
param.CreateParameter(SQL_INTEGER, SQL_PARAM_INPUT);
cmd.Parameters().Add(param);
cmd.Parameters()[0] = "Mike";
cmd.Parameters()[1] = 'M';
cmd.Parameters()[2] = "2000-1-1";
cmd.Parameters()[3] = 25;
cmd.Execute();
cmd.Parameters()[0] = "Jane";
cmd.Parameters()[1] = 'F';
cmd.Parameters()[2] = "1999-10-20";
cmd.Parameters()[3] = 22;
cmd.Execute();
cmd.Close();
CSqlCommand
class provides a way to execute a SQL statement, but
doesn't provide a way to access the result set that might be generated by that
statement. To perform a query we should use CSqlRecordset
class.
CSqlRecordset rs;
rs.Create(&db);
rs.m_strFilter = "Age > ? AND Sex = ?";
CSqlParameter param;
param.CreateParameter(SQL_INTEGER, SQL_PARAM_INPUT);
rs.Parameters().Add(param);
param.CreateParameter(SQL_CHAR, SQL_PARAM_INPUT, 1);
rs.Parameters().Add(param);
rs.Parameters()[0] = 20;
rs.Parameters()[1] = "M";
CSqlField fd;
fd.CreateField("Name", SQL_C_CHAR, 20);
rs.Fields().Add(fd);
fd.CreateField("Age", SQL_C_LONG);
rs.Fields().Add(fd);
rs.SetCacheSize(10);
rs.Open("Employee", CSqlRecordset::sqlCmdTable);
rs.MoveNext();
while (!rs.IsEOF())
{
printf("Name:%s Age:%d\n", (char*)rs.Fields()[0],
(int)rs.Fields()[1]);
rs.MoveNext();
}
rs.Parameters()[0] = 30;
rs.Parameters()[1] = "F";
rs.Requery();
rs.MoveNext();
...
CSqlRecordset rs;
rs.Create(&db);
rs.AutoBindProcParams("ProcName", "SchemaName");
rs.Parameters()[0] = 1;
...
rs.Open("ProcName", CSqlRecordset::sqlCmdStoreProc,
SQL_CURSOR_FORWARD_ONLY);
printf("Store procedure return code = %d\n", rs.GetRetStatus());
rs.MoveNext();
while (!rs.IsEOF())
{
for (int n=0; n<rs.GetFields(); n++)
{
string strVal;
rs.Fields()[n].ToString(strVal);
printf("%s ", strVal.data());
}
printf("\n");
rs.MoveNext();
}
rs.Close();
There are two way to access large object (BLOB, CLOB or DBCLOB) data:
- Bind the LOB field (or parameter) to a file, by calling
CSqlField::CreateFileField
(or
CSqlParameter::CreateFileParam
);
- Bind the LOB field to a locator, then use a CSqlLocator object to manipulate
this locator.
CSqlRecordset rs;
rs.Create(&db);
CSqlField fd;
fd.CreateFileField("lob_col1");
fd = "lob_col1.txt";
rs.Fields().Add(fd);
fd.CreateField("lob_col2", SQL_C_CLOB_LOCATOR);
rs.Fields().Add(fd);
rs.Open("lob_table", CSqlRecordset::sqlCmdTable);
rs.MoveNext();
while (!rs.IsEOF())
{
FILE *pFile = fopen("lob_col1.txt", "r");
...
CSqlLocator loc;
loc.Open(&db, rs.Fields()[1]);
int nSize = loc.GetLength();
char buf[100];
loc.GetSubString(buf, 40, 80);
loc.Free();
rs.MoveNext();
}
rs.Close();
For each
CSqlDatabase
/CSqlCommand
/CSqlRecordset
object which is inherited from CSqlObject
, the application
can call its member function GetLastError
to acquire the error
information of database operation.
void HandleError(CSqlObject* pSqlObject)
{
CSqlErrorInfo e;
while (pSqlObject->GetLastError(e))
{
printf("SQL error message: %s\n", e.GetErrorText());
}
}
An alternative way is to override CSqlObject::OnSqlError
function so that the application can handle the error immediately after
it hapens.
CSqlObject
is the base class of CSqlDatabase
,
CSqlCommand
, and CSqlRecordset
. It wraps a DB2 CLI
handle (it could be a connection handle, or a statement handle), and manages the
error messages occured on this handle.
CSqlObject();
- Creates a
CSqlObject
object.
SQLHANDLE GetHandle() const;
- Returns the DB2 CLI handle.
BOOL IsOpen() const;
- Returns
TRUE
if the DB2 CLI handle has been created, otherwise
FALSE
.
CSqlDatabase* GetDatabase() const;
- Returns the pointer of the database connection this object runs upon.
virtual void Close();
- Closes handle and releases resources.
BOOL SqlCheck(SQLRETURN nSqlRet);
- Checks the return code of a DB2 CLI API call. Returns
TRUE
if
the call succeeded, otherwise FALSE
.
BOOL SetAttribute(SQLINTEGER nAttr, SQLPOINTER pValue,
SQLINTEGER nValueSize=0);
- Sets an attribute of the handle.
- Parameters
nAttr
- Specifies the identifier of the attribute.
pValue
- Pointer to the value of the attribute.
nValueSize
- If
pValue
points to a character string or a
binary buffer, this argument should be the length of the value.
BOOL GetAttribute(SQLINTEGER nAttr, SQLPOINTER pValue,
SQLINTEGER nBuffSize=0, SQLINTEGER* pnValueSize=NULL);
- Gets the current setting of an attribute of the handle.
- Parameters
nAttr
- Specifies the identifier of the attribute.
pValue
- Pointer to a buffer to retrieve the attribute value.
nBuffSize
- Specifies the length of the buffer.
pnValueSize
- Pointer to an integer to retrieve the length of the attribute value.
BOOL GetLastError(CSqlErrorInfo& rErrorInfo);
- Gets the last-error occured on this object.
CSqlDatabase
is inherited from CSqlObject
class.
CSqlDatabase();
- Creates a
CSqlDatabase
object.
static BOOL Initialize(BOOL bMultiThread=TRUE);
- Initializes a DB2 CLI environment.
- Parameters
bMultiThread
- Specifies whether the application uses DB2 CLI in a multithreading
environment.
static void Uninitialize();
- Releases the DB2 CLI environment.
- See sample
static BOOL SetEnvAttr(SQLINTEGER nAttr, SQLINTEGER nValue);
- Sets an attribute of the DB2 CLI environment.
- Parameters
nAttr
- Specifies the identifier of the attribute.
nValue
- Specifies the value of the attribute.
static BOOL GetEnvAttr(SQLINTEGER nAttr, SQLINTEGER& nValue);
- Gets the value of an attribute of the DB2 CLI environment.
- Parameters
- nAttr
- Specifies the identifier of the attribute.
- nValue
- The integer variable to retrieve the value.
BOOL Connect(PCSTR pszDB, PCSTR pszUser, PCSTR pszPwd,
DWORD dwOption=defaultOption, DWORD dwTxnIsolation=SQL_TXN_READ_COMMITTED);
- Establishes a connection to a database.
- Parameters
pszDB
- Specifies the database name.
pszUser
- Specifies the user name.
pszPwd
- Specifies the password of the user.
dwOption
- Specifies the attribute of the database connection. It can be 0 or a
combination of the following values:
readOnly
- Specifies the connection is read-only. By default it is read-write.
manualCommit
- The application must manually, explicitly commit or rollback transactions
with CommitTrans() or RollbackTrans() calls. By default DB2 implicitly commits
each statement automatically.
autoUnlock
- Specifies the read locks are released when the cursor is closed. By default
the read locks are not released automatically
dwTxnIsolation
- Sets the transaction isolation level.
- See sample
void Close();
- Closes the current database connection.
BOOL BeginTrans();
- Begins a new transaction
BOOL CommitTrans();
- Saves any changes and ends the current transaction.
BOOL RollbackTrans();
- Cancels any changes made during the current transaction and ends the
transaction.
CSqlCommand
is inherited from CSqlObject
class.
CSqlCommand();
- Creates a
CSqlCommand
object.
BOOL Create(CSqlDatabase* pDB, DWORD dwOption=defaultOption);
- Initializes a
CSqlCommand
object.
- Parameters
pDB
- Pointer to the database connection which this command runs upon.
dwOption
- Specifies the command option. It can be 0 or a combination of the following
values:
execDirect
- Executes command directly without preparation.
autoCloseCursor
- Automatically closes an open cursor if a second cursor is opened.
nonScanEscape
- Disables the scan of SQL string for escape clauses. Don't use this option to
call stored procedure.
preFetch
- Tells the server to prefetch the next block of data immediately after
sending the current block.
- See sample
virtual void Close;
- Closes the command object.
virtual void Reset();
- Unbinds all parameters and resets the command handle for reuse.
BOOL SetCommand(PCSTR lpszSQL);
- Specifies the SQL statement to be executed, and prepare the statetment if
execDirect option not specified.
- Parameters
lpszSQL
- String pointer of a SQL statement.
BOOL Execute();
- Executes the current SQL statement.
SQLINTEGER GetRowCount();
- Returns the count of rows that were affected by the SQL statement.
CSqlParameters& Parameters();
- Returns the collection of parameters bound on this command.
CSqlReco
rdset is inherited from CSqlCommand
class.
CSqlRecordset();
- Creates a
CSqlRecordset
object.
string m_strFilter;
- Specifies the search condition of the query before calling
Open()
with nCmdType
set to sqlCmdTable
.
string m_strSort;
- Specifies the sort order for the result set before calling
Open()
with nCmdType
set to sqlCmdTable
.
BOOL Open(PCSTR pszCommand, int nCmdType,
DWORD nCursorType=SQL_CURSOR_STATIC, BOOL bUseBookmarks=FALSE);
- Opens a recordset by executing a query, store procedure or generic SQL
statement.
- Parameters
pszCommand
- String pointer of the command to be executed.
nCmdType
- Specifies how the command argument
nCmdType
should be interpreted:
sqlCmdSQL
- Evaluates the command as a SQL statement.
sqlCmdTable
- Evaluates the command as a table name.
sqlCmdStoreProc
- Evaluates the command as the name of a store procedure.
nCursorType
- Specifies the type of cursor. It can be one of the following values:
SQL_CURSOR_FORWARD_ONLY
SQL_CURSOR_STATIC
(default)
SQL_CURSOR_KEYSET_DRIVEN
bUseBookmarks
- Specifies whether enable bookmark. This argument is ignored if
nCursorType
is set to
SQL_CURSOR_FORWARD_ONLY
.
- See sample
BOOL Requery();
- Re-executes the current command to refresh the entire result set.
BOOL NextRecordset();
- Clears the current recordset, and returns the next recordset by advancing
through a series of commands.
virtual void Close();
- Closes the object and releases any resources.
virtual void Reset();
- Unbinds all columns and parameters, and resets the command handle for reuse.
BOOL AutoBindProcParams(PCSTR pszProcName, PCSTR pszSchemaName=NULL);
- Retrieves all the parameters associated with a procedure and add them to
parameter list. This function must be called before
Open().
- Parameters
pszProcName
- Specifies the name of a stored procedure.
pszSchemaName
- Specifies the name of the schema which the procedure belongs to.
BOOL IsScrollable() const;
BOOL IsUpdatable() const;
- Returns
TRUE
if the current cursor is scrollable, updatable.
BOOL SetMaxRows(DWORD nMaxRows=0);
- Specifies the maximum number of rows to return from a query. The default
value is 0 means all rows are returned. Must be called before
Open().
void SetCacheSize(int nCacheSize=0);
- Specifies the number of rows of the local row cache. A reasonable cache size
can reduce the network traffic and improve performence. The default value is 1.
Must be called before
Open().
int GetCacheSize() const;
- Returns the size of the local row cache.
int GetRetStatus() const;
- Returns the return code (specified by a RETURN statement) of this stored
procedure.
SQLUSMALLINT GetRowStatus() const;
- Returns the status of current row. It can be one of the following values:
SQL_ROW_SUCCESS
- The row was successfully fetched.
SQL_ROW_ERROR
- An error occurred while fetching the row.
SQL_ROW_NOROW
- The rowset overlapped the end of the result set and no row was returned.
SQL_ROW_DELETED
- The row has been deleted (by calling
Delete()
) since it was last
fetched from this result set.
SQL_ROW_UPDATED
- The row has been updated (by calling
Update()
) since it was
last fetched from this result set.
BOOL IsDeleted() const;
- Returns
TRUE
if the current row is marked to be deleted. This
function is only valid for updatable cursor.
BOOL IsBOF() const;
BOOL IsEOF() const;
- Returns
TRUE
if the current cursor is positioned before the
first row, or after the last row.
BOOL Move(SQLINTEGER nOffset, BOOL bRefresh=FALSE);
- Moves the cursor position to the row nOffset from the current row. This
function is only valid for scrollable cursor.
- Parameters
nOffset
- Specifies the offset from the current row.
bRefresh
- Specifies whether refresh the local row cache by acquiring data from server.
BOOL MoveFirst();
BOOL MoveLast();
BOOL MovePrevious();
BOOL MoveNext();
- Moves to the first, last, previous, next row. Except
MoveNext
these functions are only valid for scrollable cursor.
- See sample
BOOL Refresh();
- Refreshes the status of current row. This function is only valid for
scrollable cursor.
BOOL GetBookmark(SqlBookmark& rBookmark);
- Gets the bookmark of the current cursor position. This function is only
valid for scrollable cursor.
- Parameters
rBookmark
- a reference to retrieve the bookmark.
BOOL SetBookmark(const SqlBookmark& rBookmark);
- Moves to the position specified by a bookmark. This function is only valid
for scrollable cursor.
- Parameters
rBookmark
- The bookmark got from
GetBookmark()
before.
BOOL Update();
BOOL Delete();
- Updates or deletes the current row. These functions are only valid for
updatable cursor.
int GetFields() const;
CSqlFields& Fields();
- Returns the collection of fields (columns) bound on this recordset.
CSqlVariant
is the base class of CSqlParameter
and
CSqlField
. It represents a variant that has standard SQL data type.
CSqlVariant();
CSqlVariant(const CSqlVariant& rVar);
- Creates a
CSqlVariant
object.
SQLSMALLINT GetSqlType() const;
SQLSMALLINT GetDataType() const;
SQLUINTEGER GetPrecision() const;
SQLSMALLINT GetScale() const;
- Returns the SQL data type, the C data type, precision, scale of the variant.
SQLINTEGER GetMaxSize() const;
- Returns the maximum length (in bytes) of the buffer of the variant.
SQLINTEGER GetDisplaySize() const;
- Returns the length (in bytes) needed to display the variant data in
character form.
SQLINTEGER GetLength() const;
- Returns the length (in bytes) of the variant value. (If the variant is a
locator, the length of locator is returned, not the LOB data). The returned
value might be
SQL_NULL_DATA
, indicates the value is null.
BOOL IsNull() const;
- Returns
TRUE
if the value is null.
void SetNull();
- Sets the value to null.
BOOL SetValue(const void* pValue, SQLINTEGER nValueSize=0);
- Sets the value of the variant without any conversion.
- Parameters
pValue
- Pointer to the value buffer.
nValueSize
- Specifies the length of the value if it is variable (string or LOB).
BOOL FromInteger(int nValue);
BOOL FromDouble(double dValue);
BOOL FromString(const char* pszValue);
- Sets the value by converting from an
int
, double
,
char*
parameter.
int ToString(std::string& strValue);
- Converts the value to a string.
operator short() const;
operator int() const;
operator double() const;
operator const char*() const;
- Converts the value to
short
, int
,
double
, char*
data type.
SQLCHAR* GetBuffer() const;
const DATE_STRUCT* GetDate() const;
const TIME_STRUCT* GetTime() const;
const TIMESTAMP_STRUCT* GetTimeStamp() const;
- Returns the pointer of the value and casts to different data types.
CSqlParameter
is inherited from CSqlVariant
class.
CreateParameter();
CreateParameter(const CSqlParameter& rValue);
- Creates a
CSqlParameter
object.
BOOL CreateParameter(SQLSMALLINT nSqlType, SQLSMALLINT nIoType,
SQLUINTEGER nPrecision=0, SQLSMALLINT nScale=0);
- Initializes a parameter.
- Parameters
nSqlType
- Specifies the SQL data type of the parameter.
nIoType
- Specifies the input/output type of the parameter. It can be one of the
following values:
SQL_PARAM_INPUT
SQL_PARAM_OUTPUT
SQL_PARAM_INPUT_OUTPUT
nPrecision
- Specifies the precision of the parameter.
- For a binary or single byte string, it is the maximum length in bytes;
- For a double byte string, it is the maximum length in double-bytes;
- For NUMERIC or DECIMAL, it is the decimal precision;
- For fixed-length data type, this argument is ignored.
- nScale
- Specifies the scale if
nSqlType
is
SQL_NUMERIC, SQL_ECIMAL
, or SQL_TIMESTAMP
.
- See sample
BOOL CreateFileParam(SQLSMALLINT nSqlType);
- Initializes a file-binding parameter. The value of this parameter is the
file name, not the LOB data.
- Parameters
nSqlType
- Specifies the SQL data type of the parameter. It only can be
SQL_BLOB
, SQL_CLOB
, or SQL_DBCLOB
.
CSqlParameter& operator=(const CSqlParameter& rValue);
CSqlParameter& operator=(int nValue);
CSqlParameter& operator=(double nValue);
CSqlParameter& operator=(const char* pszValue);
- Sets the value of the parameter.
CSqlField
is inherited from CSqlVariant
class.
CSqlField();
CSqlField(const CSqlField& rData);
- Creates a
CSqlField
object.
BOOL CreateField(PCSTR pszFieldName, SQLSMALLINT nDataType,
SQLINTEGER nDataSize=0);
- Initializes a field (column) object.
- Parameters
pszFieldName
- Specifies the name of the field. It can be a column name in a table, or a
SQL expression.
nDataType
- Specifies the C data type identifier of the field.
nDataSize
- Specifies the maximum length in bytes of the field. This argument is ignored
if
nDataType
specifies a fixed-length data type.
- See sample
BOOL CreateField(CSqlCommand* pStmt, int nOrdinal);
- Initializes a field according to the attribute of a specified column in a
recordset.
- Parameters
pStmt
- Pointer to the recordset object which contains the specified column.
nOrdinal
- The ordinal number identifying the column.
BOOL CreateFileField(PCSTR pszFieldName,
SQLUINTEGER nFileOption=SQL_FILE_OVERWRITE);
- Initializes a file-binding field. The value of this field is the file name,
not the LOB data.
- Parameters
pszFieldName
- Specifies the name of the field. It is usually the name of a LOB column in a
table.
nFileOption
- Specifies the file access option. It can be one of the following values:
SQL_FILE_CREATE
- Create a new file. If a file by this name already exists,
SQL_ERROR
will be returned.
SQL_FILE_OVERWRITE
- If the file already exists, overwrite it. Otherwise, create a new file.
SQL_FILE_APPEND
- If the file already exists, append the data to it. Otherwise, create a new
file.
- See sample
CSqlField& operator=(const CSqlField& rValue);
CSqlField& operator=(int nValue);
CSqlField& operator=(double nValue);
CSqlField& operator=(const char* pszValue);
- Sets the value of the field.
CSqlLocator
has no base class.
CSqlLocator();
- Creates a
CSqlLocator
object.
BOOL Open(CSqlDatabase* pDB, const CSqlVariant& rVariant);
- Initializes the
CSqlLocator
object.
- Parameters
pDB
- Specifies a database connection to manipulate the locator.
rVariant
- Specifies a variant (usually a field) object which represents the locator.
SQLINTEGER GetLength();
- Returns the total length of the LOB data represented by the locator.
SQLINTEGER GetSubString(SQLPOINTER pBuff, SQLINTEGER nStartPos,
SQLINTEGER nLength);
- Gets a portion from the LOB data.
- Parameters
pBuff
- Specifies a buffer to retrieve returned string.
nStartPos
- Specifies the position of the first byte to be returned.
nLength
- Specifies the length of the string to be returned.
BOOL Free();
- Frees the locator object.
- See sample
CSqlErrorInfo
has no base class.
CSqlErrorInfo();
CSqlErrorInfo(const CSqlErrorInfo& rEI);
- Creates a
CSqlErrorInfo
object.
const char* GetErrorText();
- Returns the text of an error object.
- See sample