SQL Server (OLEDB) Guide

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 OLEDB API using SQLAPI++ Library. Full information about using SQLAPI++ see in How To and Documentation.

Available topics:

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:

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

If the Library cannot find OLEDB 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);
Parameters

sDBString

A connection string like
[<server_name>@][<database_name>]
  • <server_name> - connects to a specified server. If it's ommitted SQLAPI++ tries to connect to default local server instance
  • <database_name> - connects to a database with the specified name. If it's omitted SQLAPI++ tries to connect to default database
To connect to a named instance of SQL Server use <server name\instance name> instead of <server_name> (use double back slash in C++ constants, for example "MyServer\\SQLEXPRESS@pubs").
Since SQLNCLI (SQL Server 2005) also available protocol specific server name part of the connection string:
  • lpc:<servername>[\instancename] - using shared memory
  • tcp:<servername>[\<instancename>],<port> or tcp:<IPAddress>[\<instancename>],<port> - using TCP/IP
  • np:\<computer_name>\pipe\<pipename> or np:\<IPAddress>\pipe\<pipename> - using named pipes
  • via:<servername>[\instancename],<nic_number>:<port> - using VIA
To open Compact Edition database file use <file path> connection string (see connection option also). Only UNICODE version of the SQLAPI++ can be used with SQL Server 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 - SQL Server client
  • SA_Client_NotSpecified - used by default if eSAClient parameter is omitted. You can use this default value only if you have SAConnection::setAPI method with SAPI object initialized 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 - Connect to database, 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 (OLEDB) in the following way:

SA_ReadUncommitted = ISOLATIONLEVEL_READUNCOMMITTED
SA_ReadCommitted = ISOLATIONLEVEL_READCOMMITTED
SA_RepeatableRead = ISOLATIONLEVEL_REPEATABLEREAD
SA_Serializable = ISOLATIONLEVEL_SERIALIZABLE

Also 'snapshot' isolation level supported, SA_Snapshot = ISOLATIONLEVEL_SNAPSHOT.

For more details see SAConnection::setIsolationLevel.

Working with Long or Lob (CLob, BLob) data

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

NameC++ Enum
LongBinarySA_dtLongBinary
LongCharSA_dtLongChar
BLob (Binary Large object)SA_dtBLob
CLob (Character Large object)SA_dtCLob

The table below shows how SQLAPI++ data types correspond with servers 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.

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 function return value. You can refer to this SAParam object using SQLAPI++ predefined name "RETURN_VALUE".

SQLAPI++ Library may have troubles with output [n]varchar(max)/varbinary(max) parameters because they aren't supported by some specific OLEDB API version.

For more details see SACommand::Execute, SAParam object, How To - Get 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 OLEDB API documentation.

For more details see SACommand::Cancel.

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.

An API related option must be specified in SAPI object. If an internal SAPI object used for the DBMS API initialization (implicit DBMS API initialization, see SAConnection::Connect method) the related DBMS specific options taken from initial connection object.

A connection related option may be specified in either SAPI object or SAConnection object. If it is specified in SAPI object it affects all the connections on that API.

A command related option may be specified in SAPI object, SAConnection object or SACommand object. If it is specified in a parent object it affects all the commands on that SAPI, SAConnection objects.

A parameter related option may be specified in SAPI object, SAConnection object, SACommand object or SAParam object. If it is specified in a parent object it affects all the parameters on that SAPI, SAConnection, SACommand objects.

A field related option may be specified in SAPI object, SAConnection object, SACommand object or SAField object. If it is specified in a parent object it affects all the fields on that on that SAPI, SAConnection, SACommand objects.

Specific options for SQL Server OLEDB API:

Option name / ScopeDescription

UseAPI

API related. Should be specified before the API is initialized.

Forces SQLAPI++ Library to use ODBC or OLEDB API

Valid values: "OLEDB", "ODBC"
Default value: "ODBC". SQLAPI++ uses ODBC as the default API

OLEDBProvider

API related. Should be specified before the API is initialized.

Forces SQLAPI++ Library to use specified OLEDB provider.

Valid values: empty, "SQLNCLI", "SQLOLEDB", "Microsoft.SQLSERVER.MOBILE.OLEDB.3.0"...
Default value: empty. SQLAPI++ tries to initialize "MSOLEDBSQL" first and then (if it fails) "SQLNCLI11", "SQLNCLI10", "SQLNCLI", "SQLOLEDB"
Special value (requires 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 SQL Server CE documentation for details. DBPROP_SSCE_DBPASSWORD property is set when the password is defined with the SAConnection::Connect() method.

CoInitializeEx_COINIT

API related. Should be specified before the API is initialized.

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"

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 the file path.

SSPROP_INIT_PACKETSIZET

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"
Default value: see SQLOLEDB documentation.

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: Failover partner name

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

DBPROP_INIT_TIMEOUT

Connection related. Should be specified before connection is made.

Sets the connection time out.

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

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"

UseDynamicCursor or
Scrollable

Command related. Should be specified before describing parameters or command execution.

Forces SQLAPI++ to use scrollable dynamic command handle. Sets DBPROP_OTHERINSERT = VARIANT_TRUE, DBPROP_OTHERUPDATEDELETE = VARIANT_TRUE, DBPROP_CANSCROLLBACKWARDS = VARIANT_TRUE.

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

ICommandPrepare

Command related. Should be specified before describing parameters or command execution.

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"

Execute_riid

Command related. Should be specified before describing parameters or 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)

DBPROP_COMMANDTIMEOUT

Command related. Should be specified before describing parameters or command execution.

Sets the command time out.

Valid values: String containing number of seconds before a command times out. A value of "0" indicates an infinite time-out Default value: 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 describing parameters or command execution.

Determines the behavior of a rowset after a commit operation.

Valid values: "VARIANT_TRUE", "VARIANT_FALSE". See SQLOLEDB documentation for more detailes Default value: By default SQLAPI++ doesn't change this option and uses the value set by SQLOLEDB. See SQLOLEDB documentation for details.

DBPROP_SERVERCURSOR
DBPROP_OTHERINSERT
DBPROP_OTHERUPDATEDELETE
DBPROP_OWNINSERT
DBPROP_OWNUPDATEDELETE
DBPROP_REMOVEDELETED
DBPROP_CANSCROLLBACKWARDS

Command related. Should be specified before describing parameters or 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: "VARIANT_TRUE", "VARIANT_FALSE". For DBPROP_SERVERCURSOR value "VARIANT_TRUE" means SQLOLEDB implements the rowset using a server cursor, "VARIANT_FALSE" - SQLOLEDB implements the rowset using a default result set).
Default value: By default SQLAPI++ doesn't change this option and uses the value set by SQLOLEDB. See SQLOLEDB documentation for details

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

Using native SQL Server OLEDB 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 OLEDB. To use the database API directly you have to downcast this IsaAPI pointer to the appropriate type and use its implementation-specific members. The following example shows what type cast you have to make and what additional header file you have to include to work with SQL Server OLEDB API.

Cast the result to class ssOleDbAPI:

#include "ssOleDbAPI.h"
 
IsaAPI *pResult = con.NativeAPI();
ssOleDbAPI *p_ssAPI = (ssOleDbAPI *)pResult;

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

For more details see SAConnection::NativeAPI.

Getting native SQL Server OLEDB connection related handles

You have to use native API handles when you want to call specific SQL Server OLEDB 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 example what type cast you have to make and what additional header file you have to include to work with specific SQL Server OLEDB API.

Cast the result to class ssOleDbConnectionHandles:

#include "ssOleDbAPI.h"
 
saConnectionHandles *pResult = con.NativeHandles();
ssOleDbConnectionHandles *p_ssCH = (ssOleDbConnectionHandles*)pResult;

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 OLEDB command related handles

You have to use native API handles when you want to call specific SQL Server OLEDB 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 example shows what type cast you have to make and what additional header file you have to include to work with specific SQL Server OLEDB API.

Cast the result to class ssOleDbCommandHandles:

#include "ssOleDbAPI.h"
 
saCommandHandles *pResult = cmd.NativeHandles();
ssOleDbCommandHandles *p_ssCH = (ssOleDbCommandHandles*)pResult;

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 OLEDB API 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 files are in the include subdirectory of SQLAPI++ distributions:

  • #include "SQLAPI.h" - main header, should be used whenever SQLAPI++ is used
  • #include "ssOleDbAPI.h" - SQL Server OLEDB API, should be included if direct OLEDB calls are required

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