SQL Server (OLEDB) Guide

SQLAPI++ allows to seamlessly work with a variety of SQL database servers. It provides unified API to access any database, keeping your code portable. 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.

For complete information on using SQLAPI++ check out Getting Started and Documentation. This guide covers specific information related to working with SQL Server (OLEDB) server using SQLAPI++ library in the following areas:

Connecting to a database

To connect to a database you need to initialize a connection object. 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.

Minimum Version
The SQLAPI++ library requires SQL Server OLE DB version 2.5 or higher.

After the connection is created you need to call SAConnection::Connect method to establish connection with SQL Server server:

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>][;<driver_connection_option_list>]
  • <server_name> - connects to a specified server. If it's omitted 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
  • <driver_connection_parameters_list> - SQL Server OLEDB driver specific parameters list

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).

Compact Edition Requirements
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

For more details see Getting Started - 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_ReadUncommittedISOLATIONLEVEL_READUNCOMMITTED
SA_ReadCommittedISOLATIONLEVEL_READCOMMITTED
SA_RepeatableReadISOLATIONLEVEL_REPEATABLEREAD
SA_SerializableISOLATIONLEVEL_SERIALIZABLE

In addition to the SQL-92 levels, if you specify 'snapshot' isolation level, it will be mapped as: SA_Snapshot ISOLATIONLEVEL_SNAPSHOT.

For more details see SAConnection::setIsolationLevel.

Working with Long or Lob (CLob, BLob) data

When fetching data SQLAPI++ detects data types of the columns in the result set and maps those types to internal library types. The mapping determines which native APIs the library will use for fetching LOB data.

The table below shows how SQLAPI++ maps SQL Server server data types to Long/Lob library types:

imageSA_dtLongBinary
textSA_dtLongChar
varbinary(max)SA_dtLongBinary
[n]varchar(max)SA_dtLongChar

When binding input data from your program the reverse mapping is taking place. The SQLAPI++ data type you use for input markers determines what native API program types will be used for sending Long/Lob data to the server.

The table below shows how SQLAPI++ maps its internal library types to SQL Server (OLEDB) API data types:
SA_dtLongBinaryDBTYPE_BYTES
SA_dtLongCharDBTYPE_STR, DBTYPE_WSTR
SA_dtBLobDBTYPE_BYTES
SA_dtCLobDBTYPE_STR, DBTYPE_WSTR

For additional information see Getting Started - Handle Long/CLob/BLob.

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.

Useful Article
There is a good article from Microsoft 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 difficulties with output [n]varchar(max) and varbinary(max) parameters because they are not supported by some specific OLEDB API versions.

For additional information see SACommand::Execute, SAParam object, Getting Started - Get Output Parameters.

Cancelling queries

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

  • function running asynchronously on the statement
  • 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 native SQL Server (OLEDB) documentation.

For additional information see SACommand::Cancel.

Connection, command, parameter and field options

Server specific options can be applied at the API, connection, command, parameter or field levels.

We recommend you specify each option at the appropriate level, although it is possible to specify them at the parent object level as well. In that case the option affects all the child objects.

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

Connection level options may be specified in either SAPI object or SAConnection object. If specified in SAPI object an option affects all connections on that API.

Command level options may be specified in SAPI object, SAConnection object or SACommand object. If specified in a parent object an option affects all commands on that SAPI or SAConnection object.

Parameter level options may be specified in SAPI object, SAConnection object, SACommand object or SAParam object. If specified in a parent object an option affects all parameters on that SAPI, SAConnection or SACommand object.

Field related options may be specified in SAPI object, SAConnection object, SACommand object or SAField object. If specified in a parent object an option affects all fields on that SAPI , SAConnection or SACommand object.

Specific options applicable to SQL Server (OLEDB):

UseAPI
Api Scope
Forces SQLAPI++ library to use ODBC or OLE DB API.
Valid values: "OLEDB", "ODBC"
Default value: "ODBC". SQLAPI++ uses ODBC as the default API
OLEDBProvider
Api Scope
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 "MSOLEDBSQL19" first and then (if it fails) "MSOLEDBSQL" , "SQLNCLI11", "SQLNCLI10", "SQLNCLI", "SQLOLEDB"
Special values: "CompactEdition", "CompactEdition.3.0", "CompactEdition.3.5", "CompactEdition.4.0"

Requires UNICODE SQLAPI++ build.

Can be used with SQLServer Compact Edition. 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 provide in the SAConnection::Connect method.

CoInitializeEx_COINIT
Api Scope
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 Scope
Applies if "OLEDBProvider" = "CompactEdition". Forces SQLAPI++ library to create SQLServer Compact/Mobile database before connection is established.
Valid values: "VARIANT_TRUE", "VARIANT_FALSE"
Default value: "VARIANT_FALSE"
SSPROP_INIT_AUTOTRANSLATE
Connection Scope
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 Scope
This option configures the data going over the network encryption. See SQLOLEDB documentation for more information.
Valid values: "VARIANT_TRUE", "VARIANT_FALSE", for MSOLEDBSQL19 and above the valid values are "no", "yes", "true", "false", "Optional", "Mandatory", "Strict"
Default value: see SQLOLEDB documentation
SSPROP_INIT_TRUST_SERVER_CERTIFICATE
Connection Scope
This option configures whether the server certificate will be trusted or validated.
Valid values:
  • "VARIANT_TRUE" - the server certificate is trusted
  • "VARIANT_FALSE" - the server certificate is not trusted and will be validated
Default value: see SQLOLEDB documentation
SSPROP_INIT_FILENAME
Connection Scope
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 Scope
This option configures packet size. See SQLOLEDB documentation for more information.
Valid values: Number as a string
Default value: see SQLOLEDB documentation
SSPROP_INIT_MARSCONNECTION
Connection Scope
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 Scope
Allows to set the connection mirror partner. See SQLOLEDB documentation for more information.
Valid values: Failover partner name
SSPROP_INIT_MULTISUBNETFAILOVER
Connection Scope
Configures OLE DB Driver for SQL Server to provide faster detection of and connection to the (currently) active server.
Valid values: "VARIANT_TRUE", "VARIANT_FALSE"
Default value: see MSOLEDBSQL documentation
SSPROP_INIT_APPNAME
APPNAME
Connection Scope
Specifies the client application name. See SQLOLEDB documentation for more information.
Valid values: client application name string
Default value: none
SSPROP_INIT_WSID
WSID
Connection Scope
Specifies the client workstation name. See SQLOLEDB documentation for more information.
Valid values: client workstation name string
Default value: none
SSPROP_AUTH_MODE
Connection Scope
Specifies the SQL or Active Directory authentication used. See MSOLEDBSQL documentation for more information.
Valid values: "SqlPassword" and other valid authentication mode string
Default value: none
SSPROP_AUTH_ACCESS_TOKEN
Connection Scope
Specifies the access token used to authenticate to Azure Active Directory. See MSOLEDBSQL documentation for more information.
Valid values: The string like "eyJ0eXAiOi..." - in the format extracted from an OAuth JSON response
Default value: none
DBPROP_INIT_TIMEOUT
Connection Scope
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 Scope
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
Command Scope
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 Scope
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"
UseStreamForLongOrLobParameters
Parameter Scope
Sets the IID_SequentalStream interface is used for the related parameter for the writing the long/LOB data to the server. Requires the OLEDB driver supports [N]VARACHAR(MAX) / VARBINART(MAX) data types. For using with [N]TEXT / IMAGE data types it also requires the option "ICommandPrepare" set to "SetParameterInfo" .
Valid values: "False", "0"
Default value: "True"
Execute_riid
Command Scope
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 Scope
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 Scope
Determines the behavior of a rowset after a commit operation.
Valid values: "VARIANT_TRUE", "VARIANT_FALSE"
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 Scope

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 additional information see SAOptions::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. 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. Note that using appropriate type casting depends on an API (that generally mean that you have to explicitly check client version before casting, see SAConnection::ClientVersion method).

To use native API you need to add SQL Server (OLEDB) specific #include and cast the result of SAConnection::NativeAPI to class ssOleDbAPI:

#include "ssOleDbAPI.h"

IsaAPI *pApi = con.NativeAPI();
ssOleDbAPI *pNativeAPI = (ssOleDbAPI *)pApi;

To get more information about SQL Server API functions see SQL Server (OLEDB) documentation.

For additional information 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 parameters. 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.

To access native connection handles you need to add SQL Server (OLEDB) specific #include and cast the result to class ssOleDbConnectionHandles:

#include "ssOleDbAPI.h"

saConnectionHandles *pHandles = con.NativeHandles();
ssOleDbConnectionHandles *pNativeHandles = (ssOleDbConnectionHandles*)pHandles;

To get more information about SQL Server API functions and handles see SQL Server (OLEDB) specific documentation.

For additional information 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 parameters. 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.

To access native command handles you need to add SQL Server (OLEDB) specific #include and cast the result to class ssOleDbCommandHandles:

#include "ssOleDbAPI.h"

saCommandHandles *pHandles = cmd.NativeHandles();
ssOleDbCommandHandles *pNativeHandles = (ssOleDbCommandHandles*)pHandles;

To get more information about SQL Server API functions and handles see SQL Server (OLEDB) specific documentation.

For additional information see SACommand::NativeHandles.

Error handling

When an error occurs when executing a SQL statement SQLAPI++ library throws an exception of type SAException and SAException::ErrPos method returns error position in the SQL statement.

In SQL Server (OLEDB) API SAException::ErrPos method returns the number of the line within SQL statement where the error occurred.

For additional information see Getting Started - Error Handling, SAException object.