SQL Server (ODBC) 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 (ODBC) server using SQLAPI++ library in the following areas:
- 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
- Using native API
- Getting native connection related handles
- Getting native command related handles
- Error handling
Connecting to a database
To connect to a database you need to initialize a connection object. A connection object is represented by SAConnection class.
Default API
UseAPI
connection option as "ODBC"
. If the library cannot find ODBC interface it throws an exception.Minimum Version
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
[<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_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"
).
lpc:<servername>[\instancename]
- using shared memorytcp:<servername>[\<instancename>],<port>
ortcp:<IPAddress>[\<instancename>],<port>
- using TCP/IPnp:\<computer_name>\pipe\<pipename>
ornp:\<IPAddress>\pipe\<pipename>
- using named pipesvia:<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
SA_SQLServer_Client
– SQL Server clientSA_Client_NotSpecified
– used by default ifeSAClient
parameter is omitted. You can use this default value only if you have SAConnection::setAPI method with SAPI object initialized withSA_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 (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 |
In addition to the SQL-92 levels, if you specify 'snapshot' isolation level, it will be mapped as: SA_Snapshot
→ SQL_TXN_SS_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
:
image | → | SA_dtLongBinary |
text | → | SA_dtLongChar |
varbinary(max) | → | SA_dtBLob |
[n]varchar(max) | → | SA_dtCLob |
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.
library types
to SQL Server (ODBC) API data types
:SA_dtLongBinary | → | SQL_LONGVARBINARY |
SA_dtLongChar | → | SQL_LONGVARCHAR |
SA_dtBLob | → | SQL_VARBINARY |
SA_dtCLob | → | SQL_VARCHAR |
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
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 ODBC 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 SQLCancel
function to cancel a query. To get more details see SQLCancel
function description in native SQL Server (ODBC) 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 (ODBC):
UseAPI
"OLEDB"
, "ODBC"
"ODBC"
. SQLAPI++ uses ODBC as the default APISQLNCLI.LIBS
- Windows -
"msodbcsql18.dll;msodbcsql17.dll;msodbcsql13.dll;msodbcsql11.dll;sqlncli11.dll;sqlncli10.dll;sqlncli.dll;sqlsrv32.dll"
- Linux -
"libmsodbcsql-18.so:libmsodbcsql-17.so:libmsodbcsql.so"
"STATIC"
, forces using the linked SQLServer client API functions when the library is compiled with SA_STATIC_MSSQL
build option.SQL_COPT_SS_PRESERVE_CURSORS
"SQL_PC_ON"
value defined the option allows to use the result set after the commit or rollback command called for the current transaction."SQL_PC_ON"
SQL_COPT_SS_ACCESS_TOKEN
"eyJ0eXAiOi..."
- in the format extracted from an OAuth JSON responsePreFetchRows
"1"
UseDynamicCursorScrollable
"True"
, "1"
"False"
SetCursorName
ExecDirect
"True"
, "1"
"False"
SQL_ATTR_CONCURRENCY
"SQL_CONCUR_READONLY"
, "SQL_CONCUR_VALUES"
, "SQL_CONCUR_ROWVER"
, "SQL_CONCUR_LOCK"
SQL_ATTR_CURSOR_TYPE
"SQL_CURSOR_FORWARD_ONLY"
, "SQL_CURSOR_KEYSET_DRIVEN"
, "SQL_CURSOR_DYNAMIC"
, "SQL_CURSOR_STATIC"
SQL_ATTR_CURSOR_SCROLLABLE
"SQL_NONSCROLLABLE"
, "SQL_SCROLLABLE"
SQL_ATTR_CURSOR_SENSITIVITY
"SQL_UNSPECIFIED"
, "SQL_INSENSITIVE"
, "SQL_SENSITIVE"
SQL_ATTR_QUERY_TIMEOUT
SQL_SOPT_SS_DEFER_PREPARE
"SQL_DP_OFF"
string that changes the default behavourSQL_DP_ON
is used by default)For additional information see SAOptions::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).
To use native API you need to add SQL Server (ODBC) specific #include
and cast the result of SAConnection::NativeAPI to class ssNCliAPI
:
#include "ssNcliAPI.h"
IsaAPI *pApi = con.NativeAPI();
ssNCliAPI *pNativeAPI = (ssNCliAPI *)pApi;
To get more information about SQL Server API functions see SQL Server (ODBC) documentation.
For additional information 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 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 (ODBC) specific #include
and cast the result to class ssNCliConnectionHandles
:
#include "ssNcliAPI.h"
saConnectionHandles *pHandles = con.NativeHandles();
ssNCliConnectionHandles *pNativeHandles = (ssNCliConnectionHandles*)pHandles;
To get more information about SQL Server API functions and handles see SQL Server (ODBC) specific documentation.
For additional information 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 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 (ODBC) specific #include
and cast the result to class ssNCliCommandHandles
:
#include "ssNcliAPI.h"
saCommandHandles *pHandles = cmd.NativeHandles();
ssNCliCommandHandles *pNativeHandles = (ssNCliCommandHandles*)pHandles;
To get more information about SQL Server API functions and handles see SQL Server (ODBC) 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 (ODBC) 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.