API

nanodbc is a library offering the primary API in C++ language.

All functions and classes provided by the nanodbc library reside in namespace nanodbc, all macros have prefix NANODBC_.

The entirety of nanodbc can be found within this file and nanodbc.cpp.

Defines

NANODBC_TEXT(s)
NANODBC_DEPRECATED
namespace nanodbc

The entirety of nanodbc can be found within this one namespace.

Note

This library does not make any exception safety guarantees, but should work just fine with a threading enabled ODBC driver. If you want to use nanodbc objects in threads I recommend each thread keep their own connection to the database. Otherwise you must synchronize any access to nanodbc objects.

Typedefs

typedef std::string string
typedef std::u16string wide_string
typedef wide_string::value_type wide_char_t
typedef long null_type
template<typename T>
using is_string = std::integral_constant<bool, std::is_same<typename std::decay<T>::type, std::string>::value || std::is_same<typename std::decay<T>::type, wide_string>::value>

A type trait for testing if a type is a std::basic_string compatible with the current nanodbc configuration.

template<typename T>
using is_character = std::integral_constant<bool, std::is_same<typename std::decay<T>::type, std::string::value_type>::value || std::is_same<typename std::decay<T>::type, wide_char_t>::value>

A type trait for testing if a type is a character compatible with the current nanodbc configuration.

template<typename T>
using enable_if_string = typename std::enable_if<is_string<T>::value>::type
template<typename T>
using enable_if_character = typename std::enable_if<is_character<T>::value>::type

Functions

inline result_iterator begin(result &r)

Returns an iterator to the beginning of the given result set.

inline result_iterator end(result&)

Returns an iterator to the end of a result set.

The default-constructed nanodbc::result_iterator is known as the end-of-result iterator. When a valid nanodbc::result_iterator reaches the end of the underlying result set, it becomes equal to the end-of-result iterator. Dereferencing or incrementing it further is undefined.

std::list<driver> list_drivers()

Returns a list of ODBC drivers on your system.

std::list<datasource> list_datasources()

Returns a list of ODBC data sources on your system.

result execute(connection &conn, const string &query, long batch_operations = 1, long timeout = 0)

Immediately opens, prepares, and executes the given query directly on the given connection.

See also

open(), prepare(), execute(), result, transaction

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits from occurring after each individual operation is executed.

Parameters
  • conn – The connection where the statement will be executed.

  • query – The SQL query that will be executed.

  • batch_operations – Numbers of rows to fetch per rowset, or the number of batch parameters to process.

  • timeout – The number in seconds before query timeout. Default is 0 indicating no timeout.

Returns

A result set object.

void just_execute(connection &conn, const string &query, long batch_operations = 1, long timeout = 0)

Opens, prepares, and executes query directly without creating result object.

See also

open(), prepare(), execute(), result, transaction

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits from occurring after each individual operation is executed.

Parameters
  • conn – The connection where the statement will be executed.

  • query – The SQL query that will be executed.

  • batch_operations – Rows to fetch per rowset, or number of batch parameters to process.

  • timeout – The number in seconds before query timeout. Default is 0 indicating no timeout.

Returns

A result set object.

result execute(statement &stmt, long batch_operations = 1)

Execute the previously prepared query now.

See also

open(), prepare(), execute(), result

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits from occurring after each individual operation is executed.

Parameters
  • stmt – The prepared statement that will be executed.

  • batch_operations – Rows to fetch per rowset, or the number of batch parameters to process.

Throws

database_error

Returns

A result set object.

void just_execute(statement &stmt, long batch_operations = 1)

Execute the previously prepared query now and without creating result object.

See also

open(), prepare(), execute(), result

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits from occurring after each individual operation is executed.

Parameters
  • stmt – The prepared statement that will be executed.

  • batch_operations – Rows to fetch per rowset, or the number of batch parameters to process.

Throws

database_error

Returns

A result set object.

result transact(statement &stmt, long batch_operations)

Execute the previously prepared query now.

Executes within the context of a transaction object, commits directly after execution.

See also

open(), prepare(), execute(), result, transaction

Parameters
  • stmt – The prepared statement that will be executed in batch.

  • batch_operations – Rows to fetch per rowset, or the number of batch parameters to process.

Throws

database_error

Returns

A result set object.

void just_transact(statement &stmt, long batch_operations)

Execute the previously prepared query now and without creating result object.

Executes within the context of a transaction object, commits directly after execution.

See also

open(), prepare(), execute(), result, transaction

Parameters
  • stmt – The prepared statement that will be executed in batch.

  • batch_operations – Rows to fetch per rowset, or the number of batch parameters to process.

Throws

database_error

Returns

A result set object.

void prepare(statement &stmt, const string &query, long timeout = 0)

Prepares the given statement to execute on it associated connection.

If the statement is not open throws programming_error.

See also

open()

Parameters
  • stmt – The prepared statement that will be executed in batch.

  • query – The SQL query that will be executed.

  • timeout – The number in seconds before query timeout. Default is 0 indicating no timeout.

Throws

database_error

class type_incompatible_error : public std::runtime_error
#include <nanodbc.h>

Type incompatible.

See also

Exception types

Public Functions

type_incompatible_error()
const char *what() const noexcept
class null_access_error : public std::runtime_error
#include <nanodbc.h>

Accessed null data.

See also

Exception types

Public Functions

null_access_error()
const char *what() const noexcept
class index_range_error : public std::runtime_error
#include <nanodbc.h>

Index out of range.

See also

Exception types

Public Functions

index_range_error()
const char *what() const noexcept
class programming_error : public std::runtime_error
#include <nanodbc.h>

Programming logic error.

See also

Exception types

Public Functions

explicit programming_error(const std::string &info)
const char *what() const noexcept
class database_error : public std::runtime_error
#include <nanodbc.h>

General database error.

See also

Exception types

Public Functions

database_error(void *handle, short handle_type, const std::string &info = "")

Creates runtime_error with message about last ODBC error.

Parameters
  • handle – The native ODBC statement or connection handle.

  • handle_type – The native ODBC handle type code for the given handle.

  • info – Additional info that will be appended to the beginning of the error message.

const char *what() const noexcept
long native() const noexcept
const std::string state() const noexcept

Private Members

long native_error
std::string sql_state
std::string message
struct date
#include <nanodbc.h>

A type for representing date data.

Public Members

std::int16_t year

Year [0-inf).

std::int16_t month

Month of the year [1-12].

std::int16_t day

Day of the month [1-31].

struct time
#include <nanodbc.h>

A type for representing time data.

Public Members

std::int16_t hour

Hours since midnight [0-23].

std::int16_t min

Minutes after the hour [0-59].

std::int16_t sec

Seconds after the minute.

struct timestamp
#include <nanodbc.h>

A type for representing timestamp data.

Public Members

std::int16_t year

Year [0-inf).

std::int16_t month

Month of the year [1-12].

std::int16_t day

Day of the month [1-31].

std::int16_t hour

Hours since midnight [0-23].

std::int16_t min

Minutes after the hour [0-59].

std::int16_t sec

Seconds after the minute.

std::int32_t fract

Fractional seconds.

class transaction
#include <nanodbc.h>

A resource for managing transaction commits and rollbacks.

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits from occurring after each individual operation is executed.

Public Functions

explicit transaction(const class connection &conn)

Begin a transaction on the given connection object.

Throws

database_error

Post

Operations that modify the database must now be committed before taking effect.

transaction(const transaction &rhs)

Copy constructor.

transaction(transaction &&rhs) noexcept

Move constructor.

transaction &operator=(transaction rhs)

Assignment.

void swap(transaction &rhs) noexcept

Member swap.

~transaction() noexcept

If this transaction has not been committed, will will rollback any modifying ops.

void commit()

Commits transaction immediately.

Throws

database_error

void rollback() noexcept

Marks this transaction for rollback.

class connection &connection()

Returns the connection object.

const class connection &connection() const

Returns the connection object.

operator class connection&()

Returns the connection object.

operator const class connection&() const

Returns the connection object.

Private Members

std::shared_ptr<transaction_impl> impl_

Friends

friend class nanodbc::connection
class statement
#include <nanodbc.h>

Represents a statement on the database.

Public Types

enum param_direction

Provides support for retrieving output/return parameters.

See also

Binding parameters

Values:

enumerator PARAM_IN

Binding an input parameter.

enumerator PARAM_OUT

Binding an output parameter.

enumerator PARAM_INOUT

Binding an input/output parameter.

enumerator PARAM_RETURN

Binding a return parameter.

Public Functions

statement()

Creates a new un-prepared statement.

explicit statement(class connection &conn)

Constructs a statement object and associates it to the given connection.

See also

open(), prepare()

Parameters

conn – The connection to use.

statement(class connection &conn, const string &query, long timeout = 0)

Constructs and prepares a statement using the given connection and query.

Parameters
  • conn – The connection to use.

  • query – The SQL query statement.

  • timeout – The number in seconds before query timeout. Default: 0 meaning no timeout.

statement(const statement &rhs)

Copy constructor.

statement(statement &&rhs) noexcept

Move constructor.

statement &operator=(statement rhs)

Assignment.

void swap(statement &rhs) noexcept

Member swap.

~statement() noexcept

Closes the statement.

See also

close()

void open(class connection &conn)

Creates a statement for the given connection.

Parameters

conn – The connection where the statement will be executed.

Throws

database_error

bool open() const

Returns true if connection is open.

bool connected() const

Returns true if connected to the database.

class connection &connection()

Returns the associated connection object if any.

const class connection &connection() const

Returns the associated connection object if any.

void *native_statement_handle() const

Returns the native ODBC statement handle.

void close()

Closes the statement and frees all associated resources.

void cancel()

Cancels execution of the statement.

Throws

database_error

void prepare(class connection &conn, const string &query, long timeout = 0)

Opens and prepares the given statement to execute on the given connection.

See also

open()

Parameters
  • conn – The connection where the statement will be executed.

  • query – The SQL query that will be executed.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Throws

database_error

void prepare(const string &query, long timeout = 0)

Prepares the given statement to execute its associated connection.

See also

open()

Note

If the statement is not open throws programming_error.

Parameters
  • query – The SQL query that will be executed.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Throws

database_error

void timeout(long timeout = 0)

Sets the number in seconds before query timeout. Default is 0 indicating no timeout.

Throws

database_error

class result execute_direct(class connection &conn, const string &query, long batch_operations = 1, long timeout = 0)

Opens, prepares, and executes the given query directly on the given connection.

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits occurring after each individual operation is executed.

Parameters
  • conn – The connection where the statement will be executed.

  • query – The SQL query that will be executed.

  • batch_operations – Numbers of rows to fetch per rowset, or the number of batch parameters to process.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Returns

A result set object.

bool async_prepare(const string &query, void *event_handle, long timeout = 0)

Prepare the given statement, in asynchronous mode.

This method will only be available if nanodbc is built against ODBC headers and library that supports asynchronous mode. Such that the identifiers SQL_ATTR_ASYNC_STMT_EVENT and SQLCompleteAsync are extant. Otherwise this method will be defined, but not implemented.

Asynchronous features can be disabled entirely by defining NANODBC_DISABLE_ASYNC when building nanodbc.

Note

If the statement is not open throws programming_error.

Parameters
  • event_handle – The event handle the caller will wait before calling complete_prepare.

  • query – The SQL query that will be prepared.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Throws

database_error

Returns

Boolean: true if the event handle needs to be awaited, false is result is ready now.

void complete_prepare()

Completes a previously initiated asynchronous query preparation.

This method will only be available if nanodbc is built against ODBC headers and library that supports asynchronous mode. Such that the identifiers SQL_ATTR_ASYNC_STMT_EVENT and SQLCompleteAsync are extant. Otherwise this method will be defined, but not implemented.

Asynchronous features can be disabled entirely by defining NANODBC_DISABLE_ASYNC when building nanodbc.

See also

async_prepare()

Throws

database_error

bool async_execute_direct(class connection &conn, void *event_handle, const string &query, long batch_operations = 1, long timeout = 0)

Opens, prepares, and executes query directly on the given connection, in async mode.

This method will only be available if nanodbc is built against ODBC headers and library that supports asynchronous mode. Such that the identifiers SQL_ATTR_ASYNC_STMT_EVENT and SQLCompleteAsync are extant. Otherwise this method will be defined, but not implemented.

Asynchronous features can be disabled entirely by defining NANODBC_DISABLE_ASYNC when building nanodbc.

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits after each individual operation is executed.

Parameters
  • conn – The connection where the statement will be executed.

  • event_handle – The event handle the caller will wait before calling complete_execute.

  • query – The SQL query that will be executed.

  • batch_operations – Rows to fetch per rowset or number of batch parameters to process.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Throws

database_error

Returns

Boolean: true if event handle needs to be awaited, false if result ready now.

bool async_execute(void *event_handle, long batch_operations = 1, long timeout = 0)

Execute the previously prepared query now, in asynchronous mode.

This method will only be available if nanodbc is built against ODBC headers and library that supports asynchronous mode. Such that the identifiers SQL_ATTR_ASYNC_STMT_EVENT and SQLCompleteAsync are extant. Otherwise this method will be defined, but not implemented.

Asynchronous features can be disabled entirely by defining NANODBC_DISABLE_ASYNC when building nanodbc.

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits after each individual operation is executed.

Parameters
  • event_handle – The event handle the caller will wait before calling complete_execute.

  • batch_operations – Rows to fetch per rowset or number of batch parameters to process.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Throws

database_error

Returns

Boolean: true if event handle needs to be awaited, false if result is ready now.

class result complete_execute(long batch_operations = 1)

Completes a previously initiated asynchronous query execution, returning the result.

This method will only be available if nanodbc is built against ODBC headers and library that supports asynchronous mode. Such that the identifiers SQL_ATTR_ASYNC_STMT_EVENT and SQLCompleteAsync are extant. Otherwise this method will be defined, but not implemented.

Asynchronous features can be disabled entirely by defining NANODBC_DISABLE_ASYNC when building nanodbc.

Throws

database_error

Parameters

batch_operations – Rows to fetch per rowset or number of batch parameters to process.

Returns

A result set object.

NANODBC_DEPRECATED class result async_complete (long batch_operations=1)

Completes a previously initiated asynchronous query execution, returning the result.

Deprecated:

Use complete_execute instead.

void enable_async(void *event_handle)

undocumented - for internal use only (used from result_impl)

void disable_async() const

undocumented - for internal use only (used from result_impl)

void just_execute_direct(class connection &conn, const string &query, long batch_operations = 1, long timeout = 0)

Execute the previously prepared query now without constructing result object.

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits after each individual operation is executed.

Parameters
  • conn – The connection where the statement will be executed.

  • query – The SQL query that will be executed.

  • batch_operations – Rows to fetch per rowset, or number of batch parameters to process.

  • timeout – Seconds before query timeout. Default is 0 indicating no timeout.

Throws

database_error

Returns

A result set object.

class result execute(long batch_operations = 1, long timeout = 0)

Execute the previously prepared query now.

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits after each individual operation is executed.

Parameters
  • batch_operations – Rows to fetch per rowset, or number of batch parameters to process.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Throws

database_error

Returns

A result set object.

void just_execute(long batch_operations = 1, long timeout = 0)

Execute the previously prepared query now without constructing result object.

Attention

You will want to use transactions if you are doing batch operations because it will prevent auto commits after each individual operation is executed.

Parameters
  • batch_operations – Rows to fetch per rowset, or number of batch parameters to process.

  • timeout – The number in seconds before query timeout. Default 0 meaning no timeout.

Throws

database_error

Returns

A result set object.

class result procedure_columns(const string &catalog, const string &schema, const string &procedure, const string &column)

Returns the input and output paramters of the specified stored procedure.

Parameters
  • catalog – The catalog name of the procedure.

  • schema – Pattern to use for schema names.

  • procedure – The name of the procedure.

  • column – Pattern to use for column names.

Throws

database_error

Returns

A result set object.

long affected_rows() const

Returns rows affected by the request or -1 if affected rows is not available.

Throws

database_error

short columns() const

Returns the number of columns in a result set.

Throws

database_error

void reset_parameters() noexcept

Resets all currently bound parameters.

short parameters() const

Returns the number of parameters in the statement.

Throws

database_error

unsigned long parameter_size(short param_index) const

Returns parameter size for indicated parameter placeholder in a prepared statement.

template<class T>
void bind(short param_index, T const *value, param_direction direction = PARAM_IN)

Binds given value to given parameter placeholder number in the prepared statement.

If your prepared SQL query has any ? placeholders, this is how you bind values to them. Placeholder numbers count from left to right and are 0-indexed.

It is NOT possible to use these functions for batch operations as number of elements is not specified here.

Parameters
  • param_index – Zero-based index of parameter marker (placeholder position).

  • value – Value to substitute into placeholder.

  • direction – ODBC parameter direction.

Throws

database_error

template<class T>
void bind(short param_index, T const *values, std::size_t batch_size, param_direction direction = PARAM_IN)

Binds multiple values.

See also

Binding multiple non-string values

template<class T>
void bind(short param_index, T const *values, std::size_t batch_size, T const *null_sentry, param_direction direction = PARAM_IN)

Binds multiple values.

See also

Binding multiple non-string values

template<class T>
void bind(short param_index, T const *values, std::size_t batch_size, bool const *nulls, param_direction direction = PARAM_IN)

Binds multiple values.

See also

Binding multiple non-string values

void bind(short param_index, std::vector<std::vector<uint8_t>> const &values, param_direction direction = PARAM_IN)

Binds multiple values.

See also

Binding multiple non-string values

void bind(short param_index, std::vector<std::vector<uint8_t>> const &values, bool const *nulls, param_direction direction = PARAM_IN)

Binds multiple values.

See also

Binding multiple non-string values

void bind(short param_index, std::vector<std::vector<uint8_t>> const &values, uint8_t const *null_sentry, param_direction direction = PARAM_IN)

Binds multiple values.

See also

Binding multiple non-string values

template<class T, typename = enable_if_character<T>>
void bind_strings(short param_index, T const *values, std::size_t value_size, std::size_t batch_size, param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

template<class T, typename = enable_if_string<T>>
void bind_strings(short param_index, std::vector<T> const &values, param_direction direction = PARAM_IN)

Binds multiple string values.

Size of the values vector indicates number of values to bind. Longest string in the array determines maximum length of individual value.

See also

bind_strings

template<std::size_t BatchSize, std::size_t ValueSize, class T, typename = enable_if_character<T>>
inline void bind_strings(short param_index, T const (&values)[BatchSize][ValueSize], param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

template<class T, typename = enable_if_character<T>>
void bind_strings(short param_index, T const *values, std::size_t value_size, std::size_t batch_size, T const *null_sentry, param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

template<class T, typename = enable_if_string<T>>
void bind_strings(short param_index, std::vector<T> const &values, typename T::value_type const *null_sentry, param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

template<std::size_t BatchSize, std::size_t ValueSize, class T, typename = enable_if_character<T>>
inline void bind_strings(short param_index, T const (&values)[BatchSize][ValueSize], T const *null_sentry, param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

template<class T, typename = enable_if_character<T>>
void bind_strings(short param_index, T const *values, std::size_t value_size, std::size_t batch_size, bool const *nulls, param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

template<class T, typename = enable_if_string<T>>
void bind_strings(short param_index, std::vector<T> const &values, bool const *nulls, param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

template<std::size_t BatchSize, std::size_t ValueSize, class T, typename = enable_if_character<T>>
inline void bind_strings(short param_index, T const (&values)[BatchSize][ValueSize], bool const *nulls, param_direction direction = PARAM_IN)

Binds multiple string values.

See also

bind_strings

void bind_null(short param_index, std::size_t batch_size = 1)

Binds null values to the parameter placeholder number in the prepared statement.

If your prepared SQL query has any parameter markers, ? (question mark) placeholders, this is how you bind values to them. Parameter markers are numbered using Zero-based index from left to right.

It is possible to use this function for batch operations.

Parameters
  • param_index – Zero-based index of parameter marker (placeholder position).

  • batch_size – The number of elements being bound.

Throws

database_error

void describe_parameters(const std::vector<short> &idx, const std::vector<short> &type, const std::vector<unsigned long> &size, const std::vector<short> &scale)

Sets descriptions for parameters in the prepared statement.

If your prepared SQL query has any parameter markers, ? (question mark) placeholders this is how you can describe the SQL type, size and scale for some or all of the parameters, prior to binding any data to the parameters. Calling this method is optional: if a parameter is not described using a call to this method, then during a bind an attempt is made to identify it using a call to the ODBC SQLDescribeParam API handle. Once set, description is re-used for possibly repeated binds execution and only cleared when the statement is cleared / destroyed. Parameter markers are numbered using Zero-based index from left to right.

Parameters
  • idx – Vector of zero-based indices of parameters we are describing.

  • type – Vector of (short integer) types.

  • size – Vector of (unsigned long) sizes.

  • scale – Vector of (short integer) decimal precision / scale.

Throws

programming_error

Private Types

typedef std::function<bool(std::size_t)> null_predicate_type

Private Members

std::shared_ptr<statement_impl> impl_

Friends

friend class nanodbc::result
class connection
#include <nanodbc.h>

Manages and encapsulates ODBC resources such as the connection and environment handles.

Public Functions

connection()

Create new connection object, initially not connected.

connection(const connection &rhs)

Copy constructor.

connection(connection &&rhs) noexcept

Move constructor.

connection &operator=(connection rhs)

Assignment.

void swap(connection&) noexcept

Member swap.

connection(const string &dsn, const string &user, const string &pass, long timeout = 0)

Create new connection object and immediately connect to the given data source.

The function calls ODBC API SQLConnect.

Parameters
  • dsn – The name of the data source name (DSN).

  • user – The username for authenticating to the data source.

  • pass – The password for authenticating to the data source.

  • timeout – Seconds before connection timeout. Default 0 meaning no timeout.

Throws

database_error

connection(const string &connection_string, long timeout = 0)

Create new connection object and immediately connect using the given connection string.

The function calls ODBC API SQLDriverConnect.

Parameters
  • connection_string – The connection string for establishing a connection.

  • timeout – Seconds before connection timeout. Default is 0 indicating no timeout.

Throws

database_error

~connection() noexcept

Automatically disconnects from the database and frees all associated resources.

Will not throw even if disconnecting causes some kind of error and raises an exception. If you explicitly need to know if disconnect() succeeds, call it directly.

void allocate()

Allocate environment and connection handles.

Allows on-demand allocation of handles to configure the ODBC environment and attributes, before database connection is established. Typically, user does not have to make this call explicitly.

See also

deallocate()

Throws

database_error

void deallocate()

Release environment and connection handles.

See also

allocate()

void connect(const string &dsn, const string &user, const string &pass, long timeout = 0)

Connect to the given data source.

See also

connected()

Parameters
  • dsn – The name of the data source.

  • user – The username for authenticating to the data source.

  • pass – The password for authenticating to the data source.

  • timeout – Seconds before connection timeout. Default is 0 indicating no timeout.

Throws

database_error

void connect(const string &connection_string, long timeout = 0)

Connect using the given connection string.

See also

connected()

Parameters
  • connection_string – The connection string for establishing a connection.

  • timeout – Seconds before connection timeout. Default is 0 indicating no timeout.

Throws

database_error

bool async_connect(const string &dsn, const string &user, const string &pass, void *event_handle, long timeout = 0)

Initiate an asynchronous connection operation to the given data source.

This method will only be available if nanodbc is built against ODBC headers and library that supports asynchronous mode. Such that the identifiers SQL_ATTR_ASYNC_DBC_EVENT and SQLCompleteAsync are extant. Otherwise this method will be defined, but not implemented.

Asynchronous features can be disabled entierly by defining NANODBC_DISABLE_ASYNC when building nanodbc.

See also

connected()

Parameters
  • dsn – The name of the data source.

  • user – The username for authenticating to the data source.

  • pass – The password for authenticating to the data source.

  • event_handle – The event handle the caller will wait before calling async_complete.

  • timeout – Seconds before connection timeout. Default is 0 indicating no timeout.

Throws

database_error

Returns

Boolean: true if event handle needs to be awaited, false if connection is ready now.

bool async_connect(const string &connection_string, void *event_handle, long timeout = 0)

Initiate an asynchronous connection operation using the given connection string.

This method will only be available if nanodbc is built against ODBC headers and library that supports asynchronous mode. Such that the identifiers SQL_ATTR_ASYNC_DBC_EVENT and SQLCompleteAsync are extant. Otherwise this method will be defined, but not implemented.

Asynchronous features can be disabled entierly by defining NANODBC_DISABLE_ASYNC when building nanodbc.

See also

connected()

Parameters
  • connection_string – The connection string for establishing a connection.

  • event_handle – Event handle the caller will wait before calling async_complete.

  • timeout – Seconds before connection timeout. Default is 0 indicating no timeout.

Throws

database_error

Returns

Boolean: true if event handle needs to be awaited, false if connection is ready now.

void async_complete()

Completes a previously initiated asynchronous connection operation.

Asynchronous features can be disabled entierly by defining NANODBC_DISABLE_ASYNC when building nanodbc.

bool connected() const

Returns true if connected to the database.

void disconnect()

Disconnects from the database, but maintains environment and handle resources.

std::size_t transactions() const

Returns the number of transactions currently held for this connection.

void *native_dbc_handle() const

Returns the native ODBC database connection handle.

void *native_env_handle() const

Returns the native ODBC environment handle.

template<class T>
T get_info(short info_type) const

Returns information from the ODBC connection as a string or fixed-size value. The general information about the driver and data source associated with a connection is obtained using SQLGetInfo function.

string dbms_name() const

Returns name of the DBMS product. Returns the ODBC information type SQL_DBMS_NAME of the DBMS product accesssed by the driver via the current connection.

string dbms_version() const

Returns version of the DBMS product. Returns the ODBC information type SQL_DBMS_VER of the DBMS product accesssed by the driver via the current connection.

string driver_name() const

Returns the name of the ODBC driver.

Throws

database_error

string database_name() const

Returns the name of the currently connected database. Returns the current SQL_DATABASE_NAME information value associated with the connection.

string catalog_name() const

Returns the name of the current catalog. Returns the current setting of the connection attribute SQL_ATTR_CURRENT_CATALOG.

Private Functions

std::size_t ref_transaction()
std::size_t unref_transaction()
bool rollback() const
void rollback(bool onoff)

Private Members

std::shared_ptr<connection_impl> impl_

Friends

friend class nanodbc::transaction::transaction_impl
class result
#include <nanodbc.h>

A resource for managing result sets from statement execution.

Note

result objects may be copied, however all copies will refer to the same result set.

Public Functions

result()

Empty result set.

~result() noexcept

Free result set.

result(const result &rhs)

Copy constructor.

result(result &&rhs) noexcept

Move constructor.

result &operator=(result rhs)

Assignment.

void swap(result &rhs) noexcept

Member swap.

void *native_statement_handle() const

Returns the native ODBC statement handle.

long rowset_size() const noexcept

The rowset size for this result set.

long affected_rows() const

Number of affected rows by the request or -1 if the affected rows is not available.

Throws

database_error

bool has_affected_rows() const

Reports if number of affected rows is available.

Throws

database_error

assert(r.has_affected_rows() == (r.affected_rows() >= 0));

Returns

true if number of affected rows is known, regardless of the value; false if the number is not available.

long rows() const noexcept

Rows in the current rowset or 0 if the number of rows is not available.

short columns() const

Returns the number of columns in a result set.

Throws

database_error

bool first()

Fetches the first row in the current result set.

Throws

database_error

Returns

true if there are more results or false otherwise.

bool last()

Fetches the last row in the current result set.

Throws

database_error

Returns

true if there are more results or false otherwise.

bool next()

Fetches the next row in the current result set.

Throws

database_error

Returns

true if there are more results or false otherwise.

bool async_next(void *event_handle)

Initiates an asynchronous fetch of the next row in the current result set.

Throws

database_error

Returns

true if the caller needs to wait for the event to be signalled, false if complete_next() can be called immediately.

bool complete_next()

Completes a previously-initiated async fetch for next row in the current result set.

Throws

database_error

Returns

true if there are more results or false otherwise.

bool prior()

Fetches the prior row in the current result set.

Throws

database_error

Returns

true if there are more results or false otherwise.

bool move(long row)

Moves to and fetches the specified row in the current result set.

Throws

database_error

Returns

true if there are results or false otherwise.

bool skip(long rows)

Skips a number of rows and then fetches the resulting row in the current result set.

Throws

database_error

Returns

true if there are results or false otherwise.

unsigned long position() const

Returns the row position in the current result set.

bool at_end() const noexcept

Returns true if there are no more results in the current result set.

void unbind()

Unbind data buffers for all columns in the result set.

Wraps unbind(short column)

Throws

index_range_error

void unbind(const string &column_name)

Unbind data buffers for specific columns in the result set.

Wraps unbind(short column)

Parameters

column_name – string Name of column we wish to unbind.

Throws

index_range_error

void unbind(short column)

Unbind data buffers for specific columns in the result set.

When a result is constructed, in order to optimize data retrieval, we automatically try to bind buffers, except for columns that contain long/blob data types. This method gives the caller the option to unbind a specific buffer. Subsequently, during calls to get(), if there is no bound data buffer, we will attempt to retrieve the data using a call SQLGetData; this is similar to the route taken for columns hosting long or bloby data types. This is suboptimal from efficiency perspective, however may be necessary of the driver we are communicating with does not support out-of-order retrieval of long data.

Parameters

column – short Zero-based index of column we wish to unbind.

Throws

index_range_error

template<class T>
void get_ref(short column, T &result) const

Gets data from the given column of the current rowset.

Columns are numbered from left to right and 0-indexed.

Parameters
  • column – position.

  • result – The column’s value will be written to this parameter.

Throws

database_error

template<class T>
void get_ref(short column, const T &fallback, T &result) const

Gets data from the given column of the current rowset.

If the data is null, fallback is returned instead.

Columns are numbered from left to right and 0-indexed.

Parameters
  • column – position.

  • fallback – if value is null, return fallback instead.

  • result – The column’s value will be written to this parameter.

Throws

database_error

template<class T>
void get_ref(const string &column_name, T &result) const

Gets data from the given column by name of the current rowset.

Parameters
  • column_name – column’s name.

  • result – The column’s value will be written to this parameter.

Throws

database_error

template<class T>
void get_ref(const string &column_name, const T &fallback, T &result) const

Gets data from the given column by name of the current rowset.

If the data is null, fallback is returned instead.

Parameters
  • column_name – column’s name.

  • fallback – if value is null, return fallback instead.

  • result – The column’s value will be written to this parameter.

Throws

database_error

template<class T>
T get(short column) const

Gets data from the given column of the current rowset.

Columns are numbered from left to right and 0-indexed.

Parameters

column – position.

Throws

database_error

template<class T>
T get(short column, const T &fallback) const

Gets data from the given column of the current rowset.

If the data is null, fallback is returned instead.

Columns are numbered from left to right and 0-indexed.

Parameters
  • column – position.

  • fallback – if value is null, return fallback instead.

Throws

database_error

template<class T>
T get(const string &column_name) const

Gets data from the given column by name of the current rowset.

Parameters

column_name – column’s name.

Throws

database_error

template<class T>
T get(const string &column_name, const T &fallback) const

Gets data from the given column by name of the current rowset.

If the data is null, fallback is returned instead.

Parameters
  • column_name – column’s name.

  • fallback – if value is null, return fallback instead.

Throws

database_error

bool is_null(short column) const

Returns true if and only if the given column of the current rowset is null.

There is a bug/limitation in ODBC drivers for SQL Server (and possibly others) which causes SQLBindCol() to never write SQL_NOT_NULL to the length/indicator buffer unless you also bind the data column. nanodbc’s is_null() will return correct values for (n)varchar(max) columns when you ensure that SQLGetData() has been called for that column (i.e. after get() or get_ref() is called).

Columns are numbered from left to right and 0-indexed.

See also

get(), get_ref()

Parameters

column – position.

Throws

database_error

bool is_null(const string &column_name) const

Returns true if and only if the given column by name of the current rowset is null.

See is_null(short column) for details on a bug/limitation of some ODBC drivers.

See also

is_null()

Parameters

column_name – column’s name.

Throws

database_error

bool is_bound(short column) const

Returns true if we have bound a buffer to the given column.

Generically, nanodbc will greedily bind buffers to columns in the result set. However, we have also given the user the ability to unbind buffers via unbind() forcing nanodbc to retrieve data via SQLGetData. This method returns true if there is a buffer bound to the column.

Columns are numbered from left to right and 0-indexed.

Parameters

column – short position.

Throws

index_range_error

bool is_bound(const string &column_name) const

Returns true if we have bound a buffer to the given column.

See is_bound(short column) for details.

See also

is_bound()

Parameters

column_name – column’s name.

Throws

index_range_error

short column(const string &column_name) const

Returns the column number of the specified column name.

Columns are numbered from left to right and 0-indexed.

Parameters

column_name – column’s name.

Throws

index_range_error

string column_name(short column) const

Returns the name of the specified column.

Columns are numbered from left to right and 0-indexed.

Parameters

column – position.

Throws

index_range_error

long column_size(short column) const

Returns the size of the specified column.

Columns are numbered from left to right and 0-indexed.

Parameters

column – position.

Throws

index_range_error

long column_size(const string &column_name) const

Returns the size of the specified column by name.

int column_decimal_digits(short column) const

Returns the number of decimal digits of the specified column.

Applies to exact numeric types (scale), datetime and interval types (prcision). If the number cannot be determined or is not applicable, drivers typically return 0.

Columns are numbered from left to right and 0-indexed.

Parameters

column – position.

Throws

index_range_error

int column_decimal_digits(const string &column_name) const

Returns the number of decimal digits of the specified column by name.

int column_datatype(short column) const

Returns a identifying integer value representing the SQL type of this column.

int column_datatype(const string &column_name) const

Returns a identifying integer value representing the SQL type of this column by name.

string column_datatype_name(short column) const

Returns data source dependent data type name of this column.

The function calls SQLCoLAttribute with the field attribute SQL_DESC_TYPE_NAME to obtain the data type name. If the type is unknown, an empty string is returned.

Note

Unlike other column metadata functions (eg. column_datatype()), this function cost is an extra ODBC API call.

string column_datatype_name(const string &column_name) const

Returns data source dependent data type name of this column by name.

The function calls SQLCoLAttribute with the field attribute SQL_DESC_TYPE_NAME to obtain the data type name. If the type is unknown, an empty string is returned.

Note

Unlike other column metadata functions (eg. column_datatype()), this function cost is an extra ODBC API call.

int column_c_datatype(short column) const

Returns a identifying integer value representing the C type of this column.

int column_c_datatype(const string &column_name) const

Returns a identifying integer value representing the C type of this column by name.

bool next_result()

Returns the next result, e.g. when stored procedure returns multiple result sets.

explicit operator bool() const

If and only if result object is valid, returns true.

Private Functions

result(statement statement, long rowset_size)

Private Members

std::shared_ptr<result_impl> impl_

Friends

friend class nanodbc::statement::statement_impl
friend class nanodbc::catalog
class result_iterator
#include <nanodbc.h>

Single pass input iterator that accesses successive rows in the attached result set.

Public Types

typedef std::input_iterator_tag iterator_category

Category of iterator.

typedef result value_type

Values returned by iterator access.

typedef result *pointer

Pointer to iteration values.

typedef result &reference

Reference to iteration values.

typedef std::ptrdiff_t difference_type

Iterator difference.

Public Functions

result_iterator() = default

Default iterator; an empty result set.

inline explicit result_iterator(result &r)

Create result iterator for a given result set.

inline reference operator*()

Dereference.

inline pointer operator->()

Access through dereference.

inline result_iterator &operator++()

Iteration.

inline result_iterator operator++(int)

Iteration.

inline bool operator==(result_iterator const &rhs) const

Iterators are equal if they a tied to the same native statemnt handle, or both empty.

inline bool operator!=(result_iterator const &rhs) const

Iterators are not equal if they have different native statemnt handles.

Private Members

result result_
class catalog
#include <nanodbc.h>

A resource for get catalog information from connected data source.

Queries are performed using the Catalog Functions in ODBC. All provided operations are convenient wrappers around the ODBC API The original ODBC behaviour should not be affected by any added processing.

Public Functions

explicit catalog(connection &conn)

Creates catalog operating on database accessible through the specified connection.

catalog::tables find_tables(const string &table = string(), const string &type = string(), const string &schema = string(), const string &catalog = string())

Creates result set with catalogs, schemas, tables, or table types.

Tables information is obtained by executing SQLTable function within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of the SQLTables, it returns result set ordered by TABLE_TYPE, TABLE_CAT, TABLE_SCHEM, and TABLE_NAME.

All arguments are treated as the Pattern Value Arguments. Empty string argument is equivalent to passing the search pattern ‘’.

catalog::table_privileges find_table_privileges(const string &catalog, const string &table = string(), const string &schema = string())

Creates result set with tables and the privileges associated with each table. Tables information is obtained by executing SQLTablePrivileges function within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of the SQLTablePrivilegess, it returns result set ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, PRIVILEGE, and GRANTEE.

Note

Due to the fact catalog cannot is not the Pattern Value Argument, order of parameters is different than in the other catalog look-up functions.

Parameters
  • catalog – The table catalog. It cannot contain a string search pattern.

  • schema – String search pattern for schema names, treated as the Pattern Value Arguments.

  • table – String search pattern for table names, treated as the Pattern Value Arguments.

catalog::columns find_columns(const string &column = string(), const string &table = string(), const string &schema = string(), const string &catalog = string())

Creates result set with columns in one or more tables.

Columns information is obtained by executing SQLColumns function within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of the SQLColumns, it returns result set ordered by TABLE_CAT, TABLE_SCHEM, TABLE_NAME, and ORDINAL_POSITION.

All arguments are treated as the Pattern Value Arguments. Empty string argument is equivalent to passing the search pattern ‘’.

catalog::primary_keys find_primary_keys(const string &table, const string &schema = string(), const string &catalog = string())

Creates result set with columns that compose the primary key of a single table.

Returns result set with column names that make up the primary key for a table. The primary key information is obtained by executing SQLPrimaryKey function within scope of the connected database accessible with the specified connection.

All arguments are treated as the Pattern Value Arguments. Empty string argument is equivalent to passing the search pattern ‘’.

catalog::procedures find_procedures(const string &procedure = string(), const string &schema = string(), const string &catalog = string())

Creates result set with catalog, schema, procedure, and procedure types.

Procedure information is obtained by executing SQLProcedures function within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of the SQLProceduress, it returns result set ordered by PROCEDURE_CAT, PROCEDUORE_SCHEM, and PROCEDURE_NAME.

All arguments are treated as the Pattern Value Arguments. Empty string argument is equivalent to passing the search pattern ‘’.

catalog::procedure_columns find_procedure_columns(const string &column = string(), const string &procedure = string(), const string &schema = string(), const string &catalog = string())

Creates result set with columns in one or more procedures.

Columns information is obtained by executing SQLProcedureColumns function within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of the SQLProcedureColumns, it returns result set ordered by PROCEDURE_CAT, PROCEDURE_SCHEM, PROCEDURE_NAME, and COLUMN_TYPE.

All arguments are treated as the Pattern Value Arguments. Empty string argument is equivalent to passing the search pattern ‘’.

std::list<string> list_catalogs()

Returns names of all catalogs (or databases) available in connected data source.

Executes SQLTable function with SQL_ALL_CATALOG as catalog search pattern.

std::list<string> list_schemas()

Returns names of all schemas available in connected data source.

Executes SQLTable function with SQL_ALL_SCHEMAS as schema search pattern.

Private Members

connection conn_
class columns
#include <nanodbc.h>

Result set for a list of columns in one or more tables.

Public Functions

bool next()

Move to the next result in the result set.

string table_catalog() const

Fetch table catalog.

string table_schema() const

Fetch table schema.

string table_name() const

Fetch table name.

string column_name() const

Fetch column name.

short data_type() const

Fetch column data type.

string type_name() const

Fetch column type name.

long column_size() const

Fetch column size.

long buffer_length() const

Fetch buffer length.

short decimal_digits() const

Fetch decimal digits.

short numeric_precision_radix() const

Fetch numeric precission.

short nullable() const

True iff column is nullable.

string remarks() const

Fetch column remarks.

string column_default() const

Fetch column’s default.

short sql_data_type() const

Fetch column’s SQL data type.

short sql_datetime_subtype() const

Fetch datetime subtype of column.

long char_octet_length() const

Fetch char octet length.

long ordinal_position() const

Ordinal position of the column in the table. The first column in the table is number 1. Returns ORDINAL_POSITION column value in result set returned by SQLColumns.

string is_nullable() const

Fetch column is-nullable information.

Note

MSDN: This column returns a zero-length string if nullability is unknown. ISO rules are followed to determine nullability. An ISO SQL-compliant DBMS cannot return an empty string.

Private Functions

columns(result &find_result)

Private Members

result result_

Friends

friend class nanodbc::catalog
class primary_keys
#include <nanodbc.h>

Result set for a list of columns that compose the primary key of a single table.

Public Functions

bool next()

Move to the next result in the result set.

string table_catalog() const

Fetch table catalog.

string table_schema() const

Fetch table schema.

string table_name() const

Fetch table name.

string column_name() const

Fetch column name.

short column_number() const

Column sequence number in the key (starting with 1). Returns valye of KEY_SEQ column in result set returned by SQLPrimaryKeys.

string primary_key_name() const

Primary key name. NULL if not applicable to the data source. Returns valye of PK_NAME column in result set returned by SQLPrimaryKeys.

Private Functions

primary_keys(result &find_result)

Private Members

result result_

Friends

friend class nanodbc::catalog
class procedure_columns
#include <nanodbc.h>

Result set for a list of procedures in the data source.

Public Functions

bool next()

Move to the next result in the result set.

string procedure_catalog() const

Fetch procedure catalog.

string procedure_schema() const

Fetch procedure schema.

string procedure_name() const

Fetch procedure name.

string column_name() const

Fetch column name.

short column_type() const

Fetch column type.

short data_type() const

Fetch column data type.

string type_name() const

Fetch column type name.

long column_size() const

Fetch column size.

long buffer_length() const

Fetch buffer length.

short decimal_digits() const

Fetch decimal digits.

short numeric_precision_radix() const

Fetch numeric precission.

short nullable() const

True iff column is nullable.

string remarks() const

Fetch column remarks.

string column_default() const

Fetch column’s default.

short sql_data_type() const

Fetch column’s SQL data type.

short sql_datetime_subtype() const

Fetch datetime subtype of column.

long char_octet_length() const

Fetch char octet length.

long ordinal_position() const

Ordinal position of the column in the table. The first column in the table is number 1. Returns ORDINAL_POSITION column value in result set returned by SQLColumns.

string is_nullable() const

Fetch column is-nullable information.

Note

MSDN: This column returns a zero-length string if nullability is unknown. ISO rules are followed to determine nullability. An ISO SQL-compliant DBMS cannot return an empty string.

Private Functions

procedure_columns(result &find_result)

Private Members

result result_

Friends

friend class nanodbc::catalog
class procedures
#include <nanodbc.h>

Result set for a list of procedures in the data source.

Public Functions

bool next()

Move to the next result in the result set.

string procedure_catalog() const

Fetch procedure catalog.

string procedure_schema() const

Fetch procedure schema.

string procedure_name() const

Fetch procedure name.

string procedure_remarks() const

Fetch procedure remarks.

short procedure_type() const

Fetch procedure type.

Private Functions

procedures(result &find_result)

Private Members

result result_

Friends

friend class nanodbc::catalog
class table_privileges
#include <nanodbc.h>

Result set for a list of tables and the privileges associated with each table.

Public Functions

bool next()

Move to the next result in the result set.

string table_catalog() const

Fetch table catalog.

string table_schema() const

Fetch table schema.

string table_name() const

Fetch table name.

string grantor() const

Fetch name of user who granted the privilege.

string grantee() const

Fetch name of user whom the privilege was granted.

string privilege() const

Fetch the table privilege.

string is_grantable() const

Fetch indicator whether the grantee is permitted to grant the privilege to other users.

Private Functions

table_privileges(result &find_result)

Private Members

result result_

Friends

friend class nanodbc::catalog
class tables
#include <nanodbc.h>

Result set for a list of tables in the data source.

Public Functions

bool next()

Move to the next result in the result set.

string table_catalog() const

Fetch table catalog.

string table_schema() const

Fetch table schema.

string table_name() const

Fetch table name.

string table_type() const

Fetch table type.

string table_remarks() const

Fetch table remarks.

Private Functions

tables(result &find_result)

Private Members

result result_

Friends

friend class nanodbc::catalog
struct driver
#include <nanodbc.h>

Information on a configured ODBC driver.

Public Members

nanodbc::string name

Driver name.

std::list<attribute> attributes

List of driver attributes.

struct attribute
#include <nanodbc.h>

Driver attributes.

Public Members

nanodbc::string keyword

Driver keyword attribute.

nanodbc::string value

Driver attribute value.

struct datasource

Public Members

nanodbc::string name

DSN name.

nanodbc::string driver

Driver description.