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)
Creates a string literal of the type corresponding to
nanodbc::string.By default, the macro maps to an unprefixed string literal. If building with options NANODBC_ENABLE_UNICODE=ON and NANODBC_USE_IODBC_WIDE_STRINGS=ON specified, then it prefixes a literal with U”…”. If only NANODBC_ENABLE_UNICODE=ON is specified, then:
If building with Visual Studio, then the macro prefixes a literal with L”…”.
Otherwise, it prefixes a literal with u”…”.
-
NANODBC_DEPRECATED
Marks a declaration as 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
- unspecified type string
stringwill bestd::u16stringorstd::32string ifNANODBC_ENABLE_UNICODEdefined.Otherwise it will be
std::string.
- unspecified type null_type
null_typewill beint64_tfor 64-bit compilations, otherwiselong.
-
class attribute
- #include <nanodbc.h>
A class representing a connection or a statement attribute.
This is the variant-free form, used where std::variant is unavailable. The caller owns whatever value_ptr refers to and must keep it alive for as long as the attribute is used.
See https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlsetconnectattr-function
Public Functions
-
inline attribute(long const &attribute, long const &string_length, std::uintptr_t value_ptr) noexcept
Creates an attribute from the three arguments the ODBC call takes.
- Parameters:
attribute – The Attribute argument of SQLSetConnectAttr or SQLSetStmtAttr.
string_length – The StringLength argument.
value_ptr – The ValuePtr argument, as an integer or a pointer.
-
inline attribute(long const &attribute, long const &string_length, std::uintptr_t value_ptr) noexcept
-
struct batch_ops
- #include <nanodbc.h>
A type capturing parameter array length as well as number of rows in a rowset of a 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) noexcept
Creates catalog operating on database accessible through the specified connection.
-
catalog::tables find_tables(string const &table = string(), string const &type = string(), string const &schema = string(), string const &catalog = string())
Creates result set with catalogs, schemas, tables, or table types.
Tables information is obtained by executing
SQLTablefunction within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of theSQLTables, 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(string const &catalog, string const &table = string(), string const &schema = string())
Creates result set with tables and the privileges associated with each table. Tables information is obtained by executing
SQLTablePrivilegesfunction within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of theSQLTablePrivilegess, 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(string const &column = string(), string const &table = string(), string const &schema = string(), string const &catalog = string())
Creates result set with columns in one or more tables.
Columns information is obtained by executing
SQLColumnsfunction within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of theSQLColumns, 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(string const &table, string const &schema = string(), string const &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
SQLPrimaryKeyfunction 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(string const &procedure = string(), string const &schema = string(), string const &catalog = string())
Creates result set with catalog, schema, procedure, and procedure types.
Procedure information is obtained by executing
SQLProceduresfunction within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of theSQLProceduress, 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(string const &column = string(), string const &procedure = string(), string const &schema = string(), string const &catalog = string())
Creates result set with columns in one or more procedures.
Columns information is obtained by executing
SQLProcedureColumnsfunction within scope of the connected database accessible with the specified connection. Since this function is implemented in terms of theSQLProcedureColumns, 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
SQLTablesfunction withSQL_ALL_CATALOGas catalog search pattern.
-
std::list<string> list_schemas()
Returns names of all schemas available in connected data source.
Executes
SQLTablesfunction withSQL_ALL_SCHEMASas schema search pattern.
-
std::list<string> list_table_types()
Returns all available table types in the connected data source.
Executes
SQLTablesfunction withSQL_ALL_TABLE_TYPESas the table type 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.
Friends
- friend class nanodbc::catalog
-
bool next()
-
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.
Friends
- friend class nanodbc::catalog
-
bool next()
-
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.
Friends
- friend class nanodbc::catalog
-
bool next()
-
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.
Friends
- friend class nanodbc::catalog
-
bool next()
-
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.
Friends
- friend class nanodbc::catalog
-
bool next()
-
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.
Friends
- friend class nanodbc::catalog
-
bool next()
-
explicit catalog(connection &conn) noexcept
-
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) noexcept
Copy constructor.
-
connection(connection &&rhs) noexcept
Move constructor.
-
connection &operator=(connection rhs) noexcept
Assignment.
-
void swap(connection&) noexcept
Member swap.
-
connection(string const &dsn, string const &user, string const &pass, long timeout = 0)
Create new connection object and immediately connect to the given data source.
The function calls ODBC API SQLConnect.
See also
- 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:
-
explicit connection(string const &connection_string, long timeout = 0)
Create new connection object and immediately connect using the given connection string.
The function calls ODBC API SQLDriverConnect.
See also
- Parameters:
connection_string – The connection string for establishing a connection.
timeout – Seconds before connection timeout. Default is 0 indicating no timeout.
- Throws:
-
~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
- Throws:
-
void deallocate()
Release environment and connection handles.
See also
-
void connect(string const &dsn, string const &user, string const &pass, long timeout = 0)
Connect to the given data source.
See also
- 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:
-
void connect(string const &connection_string, long timeout = 0)
Connect using the given connection string.
See also
- Parameters:
connection_string – The connection string for establishing a connection.
timeout – Seconds before connection timeout. Default is 0 indicating no timeout.
- Throws:
-
bool async_connect(string const &dsn, string const &user, string const &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_EVENTandSQLCompleteAsyncare extant. Otherwise this method will be defined, but not implemented.Asynchronous features can be disabled entierly by defining
NANODBC_DISABLE_ASYNCwhen building nanodbc.See also
- 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:
- Returns:
Boolean: true if event handle needs to be awaited, false if connection is ready now.
-
bool async_connect(string const &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_EVENTandSQLCompleteAsyncare extant. Otherwise this method will be defined, but not implemented.Asynchronous features can be disabled entierly by defining
NANODBC_DISABLE_ASYNCwhen building nanodbc.See also
- 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:
- 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_ASYNCwhen building nanodbc.
-
bool connected() const noexcept
Returns true if connected to the database.
-
void disconnect()
Disconnects from the database, but maintains environment and handle resources.
-
std::size_t transactions() const noexcept
Returns the number of transactions currently held for this connection.
-
void *native_dbc_handle() const noexcept
Returns the native ODBC database connection handle.
-
void *native_env_handle() const noexcept
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
SQLGetInfofunction.
-
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:
-
string driver_version() const
Returns the version of the ODBC driver.
- Throws:
-
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() noexcept
-
std::size_t unref_transaction() noexcept
-
bool rollback() const noexcept
-
void rollback(bool onoff) noexcept
Private Members
-
std::shared_ptr<connection_impl> impl_
Friends
- friend class nanodbc::transaction::transaction_impl
-
connection()
-
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, std::string const &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.
-
char const *what() const noexcept override
Returns the full message, including the driver’s own text.
-
long native() const noexcept
Returns the native error code reported by the driver.
-
std::string const &state() const noexcept
Returns the five character SQLSTATE reported by the driver.
-
database_error(void *handle, short handle_type, std::string const &info = "")
-
struct datasource
- #include <nanodbc.h>
A data source name registered with the driver manager.
-
struct date
- #include <nanodbc.h>
A type for representing date data.
-
struct driver
- #include <nanodbc.h>
Information on a configured ODBC driver.
Public Members
-
struct attribute
- #include <nanodbc.h>
Driver attributes.
-
struct attribute
-
class implementation_row_descriptor
- #include <nanodbc.h>
Provides access to metadata in the Implementation Row Descriptor (IRD) implicitly allocated for a prepared or executed statement.
The IRD contains information about the columns in a result set, such as their SQL data types, lengths, and nullability.
Public Functions
-
implementation_row_descriptor(result const &result)
Initializes IRD access from statement of executed result set.
-
implementation_row_descriptor(statement const &statement)
Initializes IRD access from prepared or executed statement.
For performance reasons, an application should ensure the statement is executed before accessing any of the IRD fields. Accessing (i.e. calls to SQLGetDescRec) the descriptor fields of prepared only statement causes a roundtrip to SQL Server.
Note
Some fields of the descriptor are available on result set retrieved from statements that generate server cursors or on executed SQL Server
SELECTstatements containing aFOR BROWSEclause (database-specific).
-
auto alloc_type() const -> short
Value of the header field
SQL_DESC_ALLOC_AUTO.
-
auto count() const noexcept -> short
Value of the header field
SQL_DESC_COUNT.
-
auto auto_unique_value(short record) const -> bool
Boolean based on value of the
SQL_DESC_AUTO_UNIQUE_VALUEfield.
-
auto base_column_name(short record) const -> string
Value of the
SQL_DESC_BASE_COLUMN_NAMEfield.
-
auto base_table_name(short record) const -> string
Value of the
SQL_DESC_BASE_TABLE_NAMEfield.
-
auto case_sensitive(short record) const -> bool
Boolean based on value of the
SQL_DESC_CASE_SENSITIVEfield.
-
auto catalog_name(short record) const -> string
Value of the
SQL_DESC_CATALOG_NAMEfield.
-
auto concise_type(short record) const -> short
Value of the
SQL_DESC_CONCISE_TYPEfield.
-
auto display_size(short record) const -> std::int64_t
Value of the
SQL_DESC_DISPLAY_SIZEfield.
-
auto fixed_prec_scale(short record) const -> short
Value of the
SQL_DESC_FIXED_PREC_SCALEfield.
-
auto label(short record) const -> string
Value of the
SQL_DESC_LABELfield.
-
auto length(short record) const -> std::uint64_t
Value of the
SQL_DESC_LENGTHfield.
-
auto local_type_name(short record) const -> string
Value of the
SQL_DESC_LOCAL_TYPE_NAMEfield.
-
auto name(short record) const -> string
Value of the
SQL_DESC_NAMEfield.
-
auto nullable(short record) const -> short
Value of the
SQL_DESC_NULLABLEfield.- Returns:
Possible return values are
SQL_NULLABLE,SQL_NO_NULLSorSQL_NULLABLE_UNKNOWN.
-
auto num_prec_radix(short record) const -> short
Value of the
SQL_DESC_NUM_PREC_RADIXfield.
-
auto octet_length(short record) const -> std::int64_t
Value of the
SQL_DESC_OCTET_LENGTHfield.
-
auto precision(short record) const -> short
Value of the
SQL_DESC_PRECISIONfield.
-
auto rowver(short record) const -> short
Value of the
SQL_DESC_ROWVERfield.
-
auto scale(short record) const -> short
Value of the
SQL_DESC_SCALEfield.
-
auto schema_name(short record) const -> string
Value of the
SQL_DESC_SCHEMA_NAMEfield.
-
auto searchable(short record) const -> short
Value of the
SQL_DESC_SEARCHABLEfield.- Returns:
Possible return values are
SQL_PRED_NONE,SQL_PRED_CHAR,SQL_PRED_BASICorSQL_PRED_SEARCHABLE.
-
auto table_name(short record) const -> string
Value of the
SQL_DESC_TABLE_NAMEfield.
-
auto type(short record) const -> short
Value of the
SQL_DESC_TYPEfield.
-
auto type_name(short record) const -> string
Value of the
SQL_DESC_TYPE_NAMEfield.
-
auto unnamed(short record) const -> bool
Boolean based on value of the
SQL_DESC_UNNAMEDfield.
-
auto unsigned_(short record) const -> bool
Boolean based on value of the
SQL_DESC_UNSIGNEDfield.
-
auto updatable(short record) const -> short
Value of the
SQL_DESC_UPDATABLEfield.- Returns:
Possible return values are
SQL_ATTR_READ_ONLY,SQL_ATTR_WRITEorSQL_ATTR_READWRITE_UNKNOWN.
Private Functions
-
void initialize_descriptor()
-
void throw_if_record_is_out_of_range(short record) const
Private Members
- friend sql_get_descr_field
-
void *statement_handle_ = {nullptr}
-
short statement_columns_count_ = {0}
-
void *descriptor_handle_ = {nullptr}
-
short descriptor_records_count_ = {0}
-
struct sql_get_descr_field
Public Functions
-
sql_get_descr_field(implementation_row_descriptor const &ird, short record, std::uint16_t field_identifier) noexcept
-
operator std::int64_t() const
-
operator std::uint64_t() const
-
operator string() const
Public Members
-
implementation_row_descriptor const &ird_
-
short record_
-
std::uint16_t field_identifier_
-
sql_get_descr_field(implementation_row_descriptor const &ird, short record, std::uint16_t field_identifier) noexcept
-
implementation_row_descriptor(result const &result)
-
class index_range_error : public std::runtime_error
- #include <nanodbc.h>
Index out of range.
See also
Exception types
-
class null_access_error : public std::runtime_error
- #include <nanodbc.h>
Accessed null data.
See also
Exception types
-
class programming_error : public std::runtime_error
- #include <nanodbc.h>
Programming logic error.
See also
Exception types
-
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() noexcept
Empty result set.
-
~result() noexcept
Free result set.
-
void *native_statement_handle() const noexcept
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:
-
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:
-
bool first()
Fetches the first row in the current result set.
- Throws:
- Returns:
true if there are more results or false otherwise.
-
bool last()
Fetches the last row in the current result set.
- Throws:
- Returns:
true if there are more results or false otherwise.
-
bool next()
Fetches the next row in the current result set.
- Throws:
- 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:
- 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:
- Returns:
true if there are more results or false otherwise.
-
bool prior()
Fetches the prior row in the current result set.
- Throws:
- 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:
- 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:
- 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:
-
void unbind(string const &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:
-
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:
-
bool is_null(short column) const
Returns true if and only if the given column of the current rowset is null.
A long column is not bound to a buffer, and most drivers leave its length/indicator unwritten at fetch even where the ODBC specification says binding the indicator alone is enough. A binary one is asked of the driver instead, which costs a call to SQLGetData asking for none of the data: the value is left where it is, so a get() or get_ref() afterwards still returns the whole of it, but it counts as visiting the column, and SQL Server requires unbound columns be visited in ascending order and refuses an earlier one afterwards with SQLSTATE 07009. Ask in the order you intend to read.
A character or fixed size column cannot be asked without spending the only read there is, so for those this reports whatever the fetch knew until a get() or get_ref() settles it. Where the driver declines to answer at all, the same applies rather than raising.
Columns are numbered from left to right and 0-indexed.
See also
get(), get_ref()
- Parameters:
column – position.
- Throws:
-
bool is_null(string const &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
- Parameters:
column_name – column’s name.
- Throws:
-
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:
-
bool is_bound(string const &column_name) const
Returns true if we have bound a buffer to the given column.
See is_bound(short column) for details.
See also
- Parameters:
column_name – column’s name.
- Throws:
-
short column(string const &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:
-
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:
-
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:
-
long column_size(string const &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:
-
int column_decimal_digits(string const &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(string const &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(string const &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(string const &column_name) const
Returns a identifying integer value representing the C type of this column by name.
-
bool column_unsigned(short column) const
SQL_TRUE if the column is unsigned (or not numeric). SQL_FALSE if the column is signed.
Signedness of some of numeric types like SQL_TINYINT depends on backend or driver. For example, if nmot unsigned, the MySQL TINYINT datatype can range from -127 to 127; whereas the SQL Server TINYINT type always ranges 0 to 255. So, unless it is an unsigned TINYINT, a MySQL TINYINT datatype should be converted to the SQL Server SMALLINT datatype.
-
bool column_unsigned(string const &column_name) const
SQL_TRUE if the column is unsigned (or not numeric). SQL_FALSE if the column is signed.
-
bool next_result()
Returns the next result, e.g. when stored procedure returns multiple result sets.
-
explicit operator bool() const noexcept
If and only if result object is valid, returns true.
Private Members
-
std::shared_ptr<result_impl> impl_
Friends
- friend class nanodbc::statement::statement_impl
- friend class nanodbc::catalog
-
result() noexcept
-
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 std::ptrdiff_t difference_type
Iterator difference.
Public Functions
-
result_iterator() = default
Default iterator; an empty result set.
-
inline result_iterator &operator++()
Iteration.
-
inline void operator++(int)
Iteration.
Note
Returns nothing, so
*it++does not compile: copies of a result_iterator share one cursor, so none can name a row the iterator has moved past. Read through*itbefore advancing.
-
inline bool operator==(result_iterator const &rhs) const noexcept
Iterators are equal if they a tied to the same native statemnt handle, or both empty.
-
inline bool operator!=(result_iterator const &rhs) const noexcept
Iterators are not equal if they have different native statemnt handles.
-
typedef std::input_iterator_tag iterator_category
-
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.
-
enumerator PARAM_IN
Public Functions
-
statement()
Creates a new un-prepared statement.
See also
execute(), just_execute(), execute_direct(), just_execute_direct(), open(), prepare()
-
explicit statement(class connection &conn)
Constructs a statement object and associates it to the given connection.
- Parameters:
conn – The connection to use.
-
explicit statement(class connection &conn, std::list<attribute> const &attributes)
Constructs a statement object and associates it to the given connection, applying the given ODBC statement attributes.
- Parameters:
conn – The connection to use.
attributes – Statement attributes to set before the statement is used.
-
statement(class connection &conn, string const &query, long timeout = 0)
Constructs and prepares a statement using the given connection and query.
See also
execute(), just_execute(), execute_direct(), just_execute_direct(), open(), prepare()
- Parameters:
conn – The connection to use.
query – The SQL query statement.
timeout – The number in seconds before query timeout. Default: 0 meaning no timeout.
-
void open(class connection &conn)
Creates a statement for the given connection.
- Parameters:
conn – The connection where the statement will be executed.
- Throws:
-
bool open() const noexcept
Returns true if connection is open.
-
bool connected() const noexcept
Returns true if connected to the database.
-
class connection &connection() noexcept
Returns the associated connection object if any.
-
const class connection &connection() const noexcept
Returns the associated connection object if any.
-
void *native_statement_handle() const noexcept
Returns the native ODBC statement handle.
-
void close()
Closes the statement and frees all associated resources.
-
void cancel()
Cancels execution of the statement.
- Throws:
-
void prepare(class connection &conn, string const &query, long timeout = 0)
Opens and prepares the given statement to execute on the given connection.
See also
- 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:
-
void prepare(string const &query, long timeout = 0)
Prepares the given statement to execute its associated connection.
See also
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:
-
void timeout(long timeout = 0)
Sets the number in seconds before query timeout. Default is 0 indicating no timeout.
- Throws:
-
class result execute_direct(class connection &conn, string const &query, long batch_operations = 1, long timeout = 0)
Opens, prepares, and executes the given query directly on the given connection.
See also
- 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.
-
class result execute_direct(class connection &conn, string const &query, batch_ops const &array_sizes, long timeout = 0)
Opens, prepares, and executes the given query directly on the given connection.
See also
- 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.
array_sizes – More granular control of rows to fetch per rowset, and 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(string const &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_EVENTandSQLCompleteAsyncare extant. Otherwise this method will be defined, but not implemented.Asynchronous features can be disabled entirely by defining
NANODBC_DISABLE_ASYNCwhen building nanodbc.See also
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:
- 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_EVENTandSQLCompleteAsyncare extant. Otherwise this method will be defined, but not implemented.Asynchronous features can be disabled entirely by defining
NANODBC_DISABLE_ASYNCwhen building nanodbc.See also
- Throws:
-
bool async_execute_direct(class connection &conn, void *event_handle, string const &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_EVENTandSQLCompleteAsyncare extant. Otherwise this method will be defined, but not implemented.Asynchronous features can be disabled entirely by defining
NANODBC_DISABLE_ASYNCwhen building nanodbc.See also
complete_execute(), open(), prepare(), execute(), result, transaction
- 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:
- 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_EVENTandSQLCompleteAsyncare extant. Otherwise this method will be defined, but not implemented.Asynchronous features can be disabled entirely by defining
NANODBC_DISABLE_ASYNCwhen building nanodbc.See also
- 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:
- 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_EVENTandSQLCompleteAsyncare extant. Otherwise this method will be defined, but not implemented.Asynchronous features can be disabled entirely by defining
NANODBC_DISABLE_ASYNCwhen building nanodbc.See also
- Throws:
- Parameters:
batch_operations – Rows to fetch per rowset or number of batch parameters to process.
- Returns:
A result set object.
-
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, string const &query, long batch_operations = 1, long timeout = 0)
Execute the previously prepared query now without constructing result object.
See also
open(), prepare(), execute(), execute_direct(), result, transaction
- 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:
- Returns:
A result set object.
-
class result execute(long batch_operations = 1, long timeout = 0)
Execute the previously prepared query now.
See also
- 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:
- 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.
See also
- 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:
- Returns:
A result set object.
-
class result procedure_columns(string const &catalog, string const &schema, string const &procedure, string const &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:
- Returns:
A result set object.
-
long affected_rows() const
Returns rows affected by the request or -1 if affected rows is not available.
- Throws:
-
short columns() const
Returns the number of columns in a result set.
- Throws:
-
void reset_parameters() noexcept
Resets all currently bound parameters.
-
short parameters() const
Returns the number of parameters in the statement.
- Throws:
-
unsigned long parameter_size(short param_index) const
Returns parameter size for indicated parameter placeholder in a prepared statement.
-
short parameter_scale(short param_index) const
Returns parameter scale for indicated parameter placeholder in a prepared statement.
-
short parameter_type(short param_index) const
Returns parameter type for indicated parameter placeholder in a prepared statement.
-
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:
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
- friend class nanodbc::table_valued_parameter::table_valued_parameter_impl
-
enum param_direction
-
class table_valued_parameter
- #include <nanodbc.h>
Support for table-valued parameter.
Public Functions
-
table_valued_parameter()
Creates a table-valued parameter that is not yet open.
-
table_valued_parameter(const table_valued_parameter &rhs) noexcept
Copy constructor.
-
table_valued_parameter(table_valued_parameter &&rhs) noexcept
Move constructor.
-
table_valued_parameter(statement &stmt, short param_index, size_t row_count)
Creates a table-valued parameter and opens it on the given statement.
See also
-
~table_valued_parameter() noexcept
Closes the parameter, if it is still open.
-
void open(statement &stmt, short param_index, std::size_t row_count)
Opens the parameter on a statement, ready for values to be bound to it.
Only one table-valued parameter may be open on a statement at a time, and it must be closed before other parameters of that statement are bound.
- Parameters:
stmt – The prepared statement carrying the parameter marker.
param_index – Zero-based index of parameter marker (placeholder position).
row_count – Number of rows that will be bound.
- Throws:
-
void close()
Finishes the parameter, so the statement can be executed or bound further.
- Throws:
-
void bind_null(short param_index)
Binds a null value to the given column of every row.
- Parameters:
param_index – Zero-based index of the column within the parameter.
- Throws:
-
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 columns of the table-valued parameter.
Describing a column up front avoids the call to SQLDescribeParam that binding would otherwise make. A description is re-used across binds until the parameter is closed.
- Parameters:
idx – Vector of zero-based indices of the columns being described.
type – Vector of (short integer) types.
size – Vector of (unsigned long) sizes.
scale – Vector of (short integer) decimal precision / scale.
- Throws:
-
short parameters() const noexcept
Returns the number of columns in the table valued parameter.
-
unsigned long parameter_size(short param_index) const
Returns parameter size for indicated column in the TVP.
-
short parameter_scale(short param_index) const
Returns parameter scale for indicated column in the TVP.
-
short parameter_type(short param_index) const
Returns parameter type for indicated column in the TVP.
Private Members
-
std::shared_ptr<table_valued_parameter_impl> impl_
Friends
- friend class statement
-
table_valued_parameter()
-
struct time
- #include <nanodbc.h>
A type for representing time data.
-
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.
-
std::int16_t year
-
struct timestampoffset
- #include <nanodbc.h>
A type for representing timestamp+offset data.
-
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:
- Post:
Operations that modify the database must now be committed before taking effect.
-
transaction(const transaction &rhs) noexcept
Copy constructor.
-
transaction(transaction &&rhs) noexcept
Move constructor.
-
transaction &operator=(transaction rhs) noexcept
Assignment.
-
void swap(transaction &rhs) noexcept
Member swap.
-
~transaction() noexcept
If this transaction has not been committed, it will rollback any modifying ops.
-
void commit()
Commits transaction immediately.
- Throws:
-
void rollback() noexcept
Marks this transaction for rollback.
-
class connection &connection() noexcept
Returns the connection object.
-
const class connection &connection() const noexcept
Returns the connection object.
-
operator class connection&() noexcept
Returns the connection object.
-
operator const class connection&() const noexcept
Returns the connection object.
Private Members
-
std::shared_ptr<transaction_impl> impl_
Friends
- friend class nanodbc::connection
-
class type_incompatible_error : public std::runtime_error
- #include <nanodbc.h>
Type incompatible.
See also
Exception types