SQL Server (ODBC) 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 (ODBC API) server 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 default API when working with SQL Server. It means that the Library sets the default value of UseAPI connection option as "ODBC". If the Library cannot find ODBC 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>][;<driver_connection_option_list>]
  • <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
  • <driver_connection_option_list> - SQL Server Native ODBC driver specific option 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

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 SQLServer ODBC version 2000.x or SQL Server Native Client (ODBC API) version 2005 and 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 ODBC in the following way:

SA_ReadUncommitted = SQL_TXN_READ_UNCOMMITTED
SA_ReadCommitted = SQL_TXN_READ_COMMITTED
SA_RepeatableRead = SQL_TXN_REPEATABLE_READ
SA_Serializable = SQL_TXN_SERIALIZABLE

Also 'snapshot' isolation level supported, SA_Snapshot = SQL_TXN_SS_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
imageSA_dtLongBinary
textSA_dtLongChar
varbinary(max)SA_dtLongChar
[n]varchar(max)SA_dtCLob

The table below shows how SQLAPI++ data types correspond with servers original data types:

SA_dtLongBinary <=> SQL_LONGVARBINARY
SA_dtLongChar <=> SQL_LONGVARCHAR
SA_dtBLob => SQL_VARBINARY
SA_dtCLob => SQL_VARCHAR

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.

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 ODBC 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 SQLCancel function to cancel a query. To get more details see SQLCancel function description in SQLServer Native Client ODBC 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 (ODBC):

Option name / ScopeDescription

UseAPI

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

Forces SQLAPI++ Library to use ODBC or OLE DB API.

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

SQLNCLI.LIBS

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

Specifies SQL Server Native client library list. SQLAPI++ tries to load libraries from this list one by one for loading SQL Server Native API.

Valid values: Any valid SQL Server ODBC/SQLNCLI library name list. Names separated by ';' on Windows or ':' on other OS.
Default value:

  • Windows - "msodbcsql17.dll;msodbcsql13.dll;msodbcsql11.dll;sqlncli11.dll;sqlncli10.dll;sqlncli.dll;sqlsrv32.dll",
  • Linux - "libmsodbcsql.so"

SQL_COPT_SS_PRESERVE_CURSORS

Connection related. Should be specified before the first connection is made.

When "SQL_PC_ON" value defined the option allows to use the result set after the commit or rollback command called for the current transaction.

Valid values: "SQL_PC_ON"
Default value: none

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 server side cursor.

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

SetCursorName

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

Allows to define the cursor name SQLAPI++ uses for the server side cursor.

Valid values: See SQLSetCursorName documentation
Default value: none

ExecDirect

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

Forces SQLAPI++ to use SQLExecDirect instead of SQLExecute API function.

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

SQL_ATTR_CONCURRENC

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

Sets the statement concurrency attribute. See SQL Server documentation for an additional information.

Valid values: "SQL_CONCUR_READONLY", "SQL_CONCUR_VALUES", "SQL_CONCUR_ROWVER", "SQL_CONCUR_LOCK"

SQL_ATTR_CURSOR_TYPE

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

Sets the statement cursor type. See SQL Server documentation for an additional information.

Valid values: "SQL_CURSOR_FORWARD_ONLY", "SQL_CURSOR_KEYSET_DRIVEN", "SQL_CURSOR_DYNAMIC", "SQL_CURSOR_STATIC"

SQL_ATTR_CURSOR_SCROLLABLE

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

Sets the statement cursor scrollable. See SQL Server documentation for an additional information.

Valid values: "SQL_NONSCROLLABLE", "SQL_SCROLLABLE"

SQL_ATTR_CURSOR_SENSITIVITY

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

Sets the statement cursor sensitivity. See SQL Server documentation for an additional information.

Valid values: "SQL_UNSPECIFIED", "SQL_INSENSITIVE", "SQL_SENSITIVE"

SQL_ATTR_QUERY_TIMEOUT

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

Sets the integer value corresponding to the number of seconds to wait for an SQL statement to execute before returning to the application.

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

Using native SQL Server ODBC 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 ODBC 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).

Cast the result to class ssNCliAPI:

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

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

For more details see SAConnection::NativeAPI.

Getting native SQL Server ODBC connection related handles

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

Cast the result to class ssNCliConnectionHandles:

#include "ssNcliAPI.h"
 
saConnectionHandles *pResult = con.NativeHandles();
ssNCliConnectionHandles *p_ssCH = (ssNCliConnectionHandles*)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 ODBC command related handles

You have to use native API handles when you want to call specific SQL Server ODBC 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 ODBC API.

Cast the result to class ssNCliConnectionHandles:

#include "ssNcliAPI.h"
 
saCommandHandles *pResult = cmd.NativeHandles();
ssNCliConnectionHandles *p_ssCH = (ssNCliConnectionHandles*)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 ODBC API SAException::ErrPos method returns the number of the line within SQL statement where an 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 "ssNcliAPI.h" - SQL Server ODBC API, should be included if any direct ODBC calls are required

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