Home How To Online Documentation Support Download Order
 

 

 


SACommand
SAConnection
SAException
SAField
SAParam
SAString
SADateTime
SANumeric

Enums and Typedefs


Server Specific Guide

SQL Server
(OLE DB)

SQLAPI++ allows to work with a number of SQL database servers. It provides common mechanisms to access database, and as a general rule they work for any database server. But each server has some specific features which a developer has to know in order to leverage server's unique features and avoid potential errors.

This page collects all specific information that concerns working with SQL Server (OLE DB API) using SQLAPI++ Library. Full information about using SQLAPI++ see in How To and Online Documentation .

Available topics:

Connecting to a database

Transaction isolation levels

Working with Long or Lob(CLob, BLob) data

Returning output parameters

Cancelling queries

Connection, command, parameter and field options

Getting native SQL Server (OLE DB) API

Getting native SQL Server (OLE DB) connection related handles

Getting native SQL Server (OLE DB) command related handles

Error handling

Special header files - Compile time

 

Connecting to a database

To connect to a database you should create a connection object and then connect it. A connection object is represented by SAConnection class.

Starting from version 4.0.3 SQLAPI++ Library uses ODBC as the default API when working with SQL Server. If you want to use OLE DB, you should set "UseAPI" connection option before specifying SQL Server client or connecting to database:

con.setOption( "UseAPI" ) = "OLEDB";

If the Library cannot find OLE DB interface it throws an exception.

After the connection is created you need to connect it to SQL Server using SAConnection::Connect method

void Connect( const SAString &sDBString, const SAString &sUserID, const SAString &sPassword, SAClient_t eSAClient = SA_Client_NotSpecified );

with the following parameters:

sDBString.       One of the following formats:

  • "" or "@" - empty string or '@' character, connects to a default database on a local server.
  • <database name> or @ <database name> - connects to a database with the specified name on your local server.
  • <server name>@ - connects to a default database on the specified server.
  • <server name>@<database name> - connects to a database with the specified name on the specified server.

To connect to a named instance of SQL Server <server name\instance name> instead of <server name> (use double back slash at C++ constants, for example "MyServer\\SQLEXPRESS@pubs").

Since SQLNCLI (SQL Server 2005) also available protocol specific server name part of the connection string:
Shared memory: lpc:<servername>[\instancename]
TCP/IP: tcp:<servername>[\<instancename>],<port> or tcp:<IPAddress>[\<instancename>],<port>
Named pipes: np:\\<computer_name>\pipe\<pipename> or np:\\<IPAddress>\pipe\<pipename>
VIA: via:<servername> [\instancename],<nic number>:<port>

To open Compact Edition database file use "<file path>" connection string (see connection option also). At the moment only UNICODE version of the SQLAPI++ can be used with SQLServer Compact Edition.

sUserID.    A string containing a user name to use when establishing the connection. If sUserID parameter is empty, SQLAPI++ Library requests a secure, or trusted, connection to SQL Server.

sPassword.    A string containing a password to use when establishing the connection.

eSAClient.    Optional. One of the following values from SAClient_t enum:

  • SA_SQLServer_Client    SQLServer client.
  • SA_Client_NotSpecified     Used by default if eSAClient parameter is omitted.  You can use this default value only if you have call SAConnection::setClient method with SA_SQLServer_Client constant before.

The SQLAPI++ Library requires SQL Server OLE DB version 2.5 or higher.

For more details see How To - Connecting to databases, SAConnection object, SAConnection::Connect.

 

Transaction isolation levels

SQL-92 defines four isolation levels, all of which are supported by SQLAPI++:

  • Read uncommitted (the lowest level where transactions are isolated just enough to ensure that physically corrupt data is not read)
  • Read committed
  • Repeatable read
  • Serializable (the highest level, where transactions are completely isolated from one another)

SQLAPI++ maps different isolation levels on SQL Server (OLE DB) in the following way:

      SA_ReadUncommitted = ISOLATIONLEVEL_READUNCOMMITTED ('Read Uncommitted')
      SA_ReadCommitted = ISOLATIONLEVEL_READCOMMITTED ('Read Committed')
      SA_RepeatableRead = ISOLATIONLEVEL_REPEATABLEREAD ('Repeatable Read')
      SA_Serializable = ISOLATIONLEVEL_SERIALIZABLE ('Serializable')

For more details see SAConnection::setIsolationLevel.

 

Working with Long or Lob(CLob, BLob) data

SQLAPI++ supports four types for working with Lob(CLob, BLob) data:

Name C enum constant
LongBinary SA_dtLongBinary
LongChar SA_dtLongChar
BLob (Binary Large object) SA_dtBLob
CLob (Character Large object) SA_dtCLob

The table below shows how SQLAPI++ data types correspond with SQL Server's (OLE DB) original data types:

SA_dtLongBinary <=> IMAGE, VARBINARY(MAX)
SA_dtLongChar <=> TEXT, [N]VARCHAR(MAX)
SA_dtBLob => IMAGE
SA_dtCLob => TEXT

For more details see How To - Working with Long or Lob(CLob, BLob) data , How To - Binding input parameters.

 

Returning output parameters

SQL Server stored procedures can have integer return codes and output parameters. The return codes and output parameters are sent in the last packet from the server and are therefore not available to the application until all result sets from stored procedure (if any) are completely processed using SACommand::FetchNext method. There is also a good article about dealing with SQL server return values and output parameters: http://msdn.microsoft.com/en-us/library/ms971497.aspx.

SQLAPI++ Library automatically creates SAParam object to represent procedure status return code or function return value. You can refer to this SAParam object using SQLAPI++ predefined name "RETURN_VALUE".

SQLAPI++ Library doesn't support input/output [n]varchar(max)/varbinary(max) parameters. They should be used for input only or for output only data.

For more details see SACommand::Execute, SACommand::FetchNext, SAParam object, How To - Returning Output Parameters.

 

Cancelling queries

Using SACommand::Cancel method you can cancel the following types of processing on a statement:

  • A function running asynchronously on the statement.
  • A function running on the statement on another thread.

SQLAPI++ calls ICommand::Cancel function to cancel a query. To get more details see ICommand::Cancel function description in SQL Server OLE DB documentation.

For more details see SACommand::Cancel, SQL Server (OLE DB) connection and command options.

 

Connection, command, parameter and field options

A server specific option can relate to a connection, command,  parameter or field. We recommend you specify each option in an appropriate object, although it is possible to specify them in the parental object as well. In that case the option affects all the child objects.

A connection related option must be specified in a  SAConnection object.

A command related option may be specified in either SAConnection object or SACommand object. If it is specified in SAConnection object it affects all the commands on that connection.

A parameter related option may be specified in SAConnection object, SACommand object or SAParam object. If it is specified in SAConnection object it affects all the commands and therefore all the parameters on that connection. If it is specified in SACommand object it affects all the parameters on that command.

A field related option may be specified in SAConnection object, SACommand object or SAField object. If it is specified in SAConnection object it affects all the commands and therefore all the fields on that connection. If it is specified in SACommand object it affects all the fields on that command.

Specific options for SQL Server (OLE DB):

Option name / Scope 

Description

UseAPI

Connection related

Forces SQLAPI++ Library to use OLE DB, ODBC or DB-Library API.
 
Valid values : "OLEDB", "ODBC" and "DB-Lib".
Default value: "ODBC". SQLAPI++ uses ODBC as the default API.

OLEDBProvider

Connection related. Should be specified before connection is made.

Forces SQLAPI++ Library to use specified OLEDB provider.

Valid values : empty, "SQLNCLI", "SQLOLEDB", "Microsoft.SQLSERVER.MOBILE.OLEDB.3.0"...
Special values (require UNICODE SQLAPI++): "CompactEdition","CompactEdition.3.0","CompactEdition.3.5","CompactEdition.4.0" can be used with SQLServer Compact Edition. Then SQLAPI++ uses "Microsoft.SQLSERVER.CE.OLEDB.4.0", "Microsoft.SQLSERVER.CE.OLEDB.3.5" or "Microsoft.SQLSERVER.MOBILE.OLEDB.3.0" OLEDB provider, sets the "Execute_riid" = "IID_IRowset" option for related SACommand instances, uses string buffer for numeric data types. The following CE options also available if this option value is used:
DBPROP_SSCE_ENCRYPTDATABASE
DBPROP_SSCE_TEMPFILE_DIRECTORY
DBPROP_SSCE_TEMPFILE_MAX_SIZE
DBPROP_SSCE_DEFAULT_LOCK_ESCALATION
DBPROP_SSCE_AUTO_SHRINK_THRESHOLD
DBPROP_SSCE_MAX_DATABASE_SIZE
DBPROP_SSCE_FLUSH_INTERVAL
DBPROP_SSCE_DEFAULT_LOCK_TIMEOUT
DBPROP_SSCE_ENCRYPTIONMODE
DBPROP_SSCE_MAXBUFFERSIZE
DBPROP_SSCE_DBCASESENSITIVE
See CE documentation. DBPROP_SSCE_DBPASSWORD property is set when the password is defined with the  SAConnection::Connect(...) method.

Default value: empty. SQLAPI++ tries to initialize "SQLNCLI11" first and then (if it fails) "SQLNCLI10", "SQLNCLI", "SQLOLEDB".

CreateDatabase

Connection related. Should be specified before connection is made.

Acts if "OLEDBProvider"="CompactEdition". Forces SQLAPI++ Library creates SQLServer Compact/Mobile database before connection is established.

Valid values: "VARIANT_TRUE", "VARIANT_FALSE".
Default value : "VARIANT_FALSE".

SSPROP_INIT_AUTOTRANSLATE

Connection related. Should be specified before connection is made. 

This option configures OEM/ANSI character translation. See SQLOLEDB documentation for more information.

Valid values: "VARIANT_TRUE", "VARIANT_FALSE".
Default value: see SQLOLEDB  documentation.

SSPROP_INIT_ENCRYPT

Connection related. Should be specified before connection is made. 

This option configures the data going over the network encryption. See SQLOLEDB documentation for more information.

Valid values: "VARIANT_TRUE", "VARIANT_FALSE".
Default value: see SQLOLEDB  documentation.

SSPROP_INIT_TRUST_SERVER_CERTIFICATE

Connection related. Should be specified before connection is made. 

This option configures the data going over the network encryption. See SQLOLEDB documentation for more information.

Valid values: "VARIANT_TRUE", "VARIANT_FALSE".
Default value: see SQLOLEDB  documentation.

SSPROP_INIT_FILENAME

Connection related. Should be specified before connection is made. 

Specifies the primary file name of an attachable database. See SQLOLEDB documentation for more information.

Valid values: String containing.

SSPROP_INIT_PACKETSIZE

Connection related. Should be specified before connection is made. 

This option configures packet size. See SQLOLEDB documentation for more information.

Valid values: String containing number.
Default value: see SQLOLEDB  documentation.

SSPROP_INIT_MARSCONNECTION

Connection related. Should be specified before connection is made. 

Forces SQLAPI++ to initiate MARS connection. See SQLOLEDB documentation for more information.

Valid values: "VARIANT_TRUE", "VARIANT_FALSE".

SSPROP_INIT_FAILOVERPARTNER

Connection related. Should be specified before connection is made. 

Allows to set the connection mirror partner. See SQLOLEDB documentation for more information.

Valid values: String containing.

SSPROP_INIT_APPNAME
or
APPNAME

Connection related. Should be specified before connection is made.

Specifies the client application name. See SQLOLEDB documentation for more information.

Valid values: client application name string.
Default value :none.

SSPROP_INIT_WSID
or
WSID

Connection related. Should be specified before connection is made.

Specifies the client workstation name. See SQLOLEDB documentation for more information.

Valid values: client workstation name string.
Default value: none.

CoInitializeEx_COINIT

Connection related. Should be specified before connection is made.

Specifies the COM library initialization mode. See SQLOLEDB documentation for more information.

Valid values: "COINIT_MULTITHREADED", "COINIT_APARTMENTTHREADED", "Skip" (SQLAPI++ doesn't initialize COM), "Default" (SQLAPI++ tries to set "COINIT_MULTITHREADED" value; if it fails, SQLAPI++ tries to set "COINIT_APARTMENTTHREADED").
Default value: "Default".

PreFetchRows

Command related. Should be specified before command execution.

Forces SQLAPI++ Library to fetch rows in bulk, rather than retrieving records one by one.

Valid values: String containing number of rows in the fetch buffer.
Default value: "1".

ICommandPrepare

Command related. Should be specified before command preparation (either explicit or implicit).

Controls current command preparation with ICommandPrepare interface.

Valid values :
  • "skip"  - skips ICommandPrepare->Prepare() call);
  • "required"  - calls ICommandPrepare->Prepare() and reports errors if any);
  • "optional" - calls ICommandPrepare->Prepare() and ignores errors if any);
  • "SetParameterInfo" - calls ICommandWithParameters::SetParameterInfo() before ICommandPrepare->Prepare(), fixes SQLOLEDB bug KB235053. SAParam scale and precision should be defined for numeric parameters before statement prepared.

Default value : "skip".

DBPROP_SERVERCURSOR

 

DBPROP_OTHERINSERT

DBPROP_OTHERUPDATEDELETE

DBPROP_OWNINSERT

DBPROP_OWNUPDATEDELETE

DBPROP_REMOVEDELETED

DBPROP_CANSCROLLBACKWARDS

 

Command related. Should be specified before command execution.

Forces SQL Server to return result sets using one of the following methods:

  • Default result sets, which:
    - provide maximal performance in fetching data;
    - support only one active statement at a time on a connection.
  • Server cursors, which:
    - support multiple active statements on a single connection;
    - can decrease performance relative to a default result set.

You can request different cursor behaviors in a rowset by setting rowset properties DBPROP_SERVERCURSOR, DBPROP_OTHERINSERT, DBPROP_OTHERUPDATEDELETE, DBPROP_OWNINSERT, DBPROP_OWNUPDATEDELETE, DBPROP_REMOVEDELETED. Some properties can be safely combined with others. See SQLOLEDB documentation to get more about how they affect SQL Server cursors.

Valid values for DBPROP_SERVERCURSOR option: "VARIANT_TRUE" (SQLOLEDB implements the rowset using a server cursor), "VARIANT_FALSE" (SQLOLEDB implements the rowset using a default result set). 

Valid values for other options : "VARIANT_TRUE", "VARIANT_FALSE". See  SQLOLEDB documantation for more detailes. 

By default SQLAPI++ doesn't change these options and uses the values set by SQLOLEDB. See SQLOLEDB documentation for details.

UseDynamicCursor
or
Scrollable

Command related. Should be specified before describing parameters or command execution.
Forces SQLAPI++ to use scrollable dynamic server side cursor. Sets DBPROP_OTHERINSERT = VARIANT_TRUE, DBPROP_OTHERUPDATEDELETE = VARIANT_TRUE, DBPROP_CANSCROLLBACKWARDS = VARIANT_TRUE.

Valid values: "True", "1". Default value: "false".

DBPROP_INIT_TIMEOUT

Connection related.

Sets Connection Time Out.

Valid values: String containing number of seconds before a connection times out. A value of "0" indicates an infinite time-out.
By default SQLAPI++ doesn't change this option and uses the value set by SQLOLEDB. See SQLOLEDB documentation for details.

DBPROP_COMMANDTIMEOUT

Command related. Should be specified before command execution.

Sets Command Time Out.

Valid values: String containing number of seconds before a command times out. A value of "0" indicates an infinite time-out.
By default SQLAPI++ doesn't change this option and uses the value set by SQLOLEDB. See SQLOLEDB documentation for details.

DBPROP_COMMITPRESERVE

Command related. Should be specified before command execution.

Determines the behavior of a rowset after a commit operation.

Valid values: "VARIANT_TRUE", "VARIANT_FALSE". See  SQLOLEDB documantation for more detailes.

Execute_riid

Command related. Should be specified before command execution.

Sets the requested interface for the rowset returned by the command. See SQLOLEDB documentation (ICommand::Execute() function) for details.

Valid values : "IID_NULL" (no rowset is returned), "IID_IRowset" (should be used with Compact Edition), "IID_IStream", "IID_ISequentialStream", "IID_IMultipleResults".
Default value : "IID_IMultipleResults" (to create multiple results).

For more details see SAConnection::setOption, SACommand::setOption, SAField::setOption, SAParam::setOption.

 

Getting native SQL Server (OLE DB) API

You can call client specific API functions which are not directly supported by SQLAPI++ Library. SAConnection::NativeAPI method returns a pointer to the set of native API functions available for SQL Server (OLE DB). To use the database API directly you have to downcast this saAPI pointer to the appropriate type and use its implementation-specific members. The following table shows what type cast you have to make and what additional header file you have to include to work with OLE DB API. Note that using appropriate type casting depends on an API version (that generally mean that you have to explicitly check client version before casting, see SAConnection::ClientVersion method).

Type casting

Additional
include file

Cast the result to class ssOleDbAPI:

saAPI *pResult = con.NativeAPI();
ssOleDbAPI *p_ssOleDbAPI = (ssOleDbAPI *)pResult;

#include <ssOleDbAPI.h>

To get more information about DBMS API functions see this DBMS specific documentation. 

For more details see SAConnection::NativeAPI.

 

Getting native SQL Server (OLE DB) connection related handles

You have to use native API handles when you want to call specific SQL Server OLE DB API functions which are not directly supported by the Library. API functions usually need to receive one or more active handles as a parameter(s). SAConnection::NativeHandles method returns a pointer to the set of native API connection related handles. To use API handles directly you have to downcast saConnectionHandles pointer to the appropriate type and use its implementation-specific members. The following table shows what type cast you have to make and what additional header file you have to include to work with specific OLE DB API. Note that using appropriate type casting depends on an API version (that generally mean that you have to explicitly check client version before casting, see SAConnection::ClientVersion method).

Type casting

Cast the result to class ssOleDbConnectionHandles:

#include <ssOleDbAPI.h>

saConnectionHandles *pResult = con.NativeHandles();
ssOleDbConnectionHandles *p_ssOleDbCH =
                                (ssOleDbConnectionHandles *)pResult;

Available handles:

  • IDBInitialize *pIDBInitialize;
  • IDBCreateCommand *pIDBCreateCommand;
  • ITransactionLocal *pITransactionLocal;

To get more information about DBMS API functions and handles see this DBMS specific documentation. 

For more details see SAConnection::NativeHandles.

 

Getting native SQL Server (OLE DB) command related handles

You have to use native API handles when you want to call specific SQL Server OLE DB API functions which are not directly supported by the Library. API functions usually need to receive one or more active handles as a parameter(s). SACommand::NativeHandles method returns a pointer to the set of native API command related handles. To use API handles directly you have to downcast saCommandHandles pointer to the appropriate type and use its implementation-specific members. The following table shows what type cast you have to make and what additional header file you have to include to work with specific SQL Server OLE DB API. Note that using appropriate type casting depends on an API version (that generally mean that you have to explicitly check client version before casting, see SAConnection::ClientVersion method).

Type casting

Cast the result to class ssOleDbCommandHandles:

#include <ssOleDbAPI.h>

saCommandHandles *pResult = cmd.NativeHandles ();
ssOleDbCommandHandles *p_ssOleDbCH =
                                 (ssOleDbCommandHandles *)pResult;

Available handles:

  • ICommandText *pICommandText;
  • IMultipleResults *pIMultipleResults;
  • IRowset *pIRowset; 

To get more information about DBMS API functions and handles see this DBMS specific documentation. 

For more details see SACommand::NativeHandles.

 

Error handling

When an error occurs inside SQLAPI++ Library it throws an exception of type SAException. SAException::ErrPos method gets an error position in SQL statement. In SQL Server (OLE DB) SAException::ErrPos method returns the number of line within SQL statement where error occurred.

For more details see How To - Error handling, SAException object.

 

Special header files - Compile time

The header file in the include subdirectory of SQLAPI++ distributions:
#include <SQLAPI.h> - main header, should be used whenever SQLAPI++ is used.
#include <ssOleDbAPI.h> - SQLServer API, should be included if direct SQL Server OLE DB calls are required.

For more details see Online Documentation - Instructions for Compiling and Linking Applications with SQLAPI++ 

 

Multithread programming

If you use SQL Server OLEDB API you must initialize/uninitialize OLE/COM library at each thread your app runs. By default SQLAPI++ does this itself but only for the first and last SAConnection instance initialized for using with SQL Server. But for the complex multi-thread app you must do this yourself. For example:
   SAConnection conMain;

   void ThreadFunc()
   {
       // You can use conMain here or another local connection:
       SAConnection con.setOption("CoInitializeEx___COINIT") = "Skip";
       ...
       con.Connect(...);
       ...
   }

   void ThreadFuncStatic()
   {
       // With this code you can be sure that no any
       // destructor is called for local SA object instance
       // after CoUninitialize
       ::CoInitializeEx(NULL, COINIT_MULTITHREADED);
       ThreadFunc();
       ::CoUninitialize();
   }

   int main(...)
   {
       ::CoInitializeEx(NULL, COINIT_MULTITHREADED);

       conMain.setOption("__CoInitializeEx_COINIT") = "Skip";

       try
       {
           conMain.setClient(SA___SQLServer_Client);
           ...
           // run ThreadFuncStatic-s here
           ...
           con.setClient(SA_Client___NotSpecified);
       }
       catch(SAException& x)
       {
           ...
       }

       ::CoUninitialize();

   }
        

Problems and Questions

If you haven't found the answer to you questions or have some problems on using the Library, please, send e-mail to howto@sqlapi.com.