pub struct ODBCConnection {
    pub connection: Option<Connection<'static>>,
    /* private fields */
}

Fields§

§connection: Option<Connection<'static>>

Implementations§

source§

impl ODBCConnection

source

pub fn detach(self) -> Connection<'static>

Methods from Deref<Target = Connection<'static>>§

source

pub fn execute( &self, query: &str, params: impl ParameterCollectionRef ) -> Result<Option<CursorImpl<StatementImpl<'_>>>, Error>

Executes an SQL statement. This is the fastest way to submit an SQL statement for one-time execution.

Parameters
  • query: The text representation of the SQL statement. E.g. “SELECT * FROM my_table;”.
  • params: ? may be used as a placeholder in the statement text. You can use () to represent no parameters. See the crate::parameter module level documentation for more information on how to pass parameters.
Return

Returns Some if a cursor is created. If None is returned no cursor has been created ( e.g. the query came back empty). Note that an empty query may also create a cursor with zero rows.

Example
use odbc_api::{Environment, ConnectionOptions};

let env = Environment::new()?;

let mut conn = env.connect(
    "YourDatabase", "SA", "My@Test@Password1",
    ConnectionOptions::default()
)?;
if let Some(cursor) = conn.execute("SELECT year, name FROM Birthdays;", ())? {
    // Use cursor to process query results.  
}
source

pub async fn execute_polling( &self, query: &str, params: impl ParameterCollectionRef, sleep: impl Sleep ) -> Result<Option<CursorPolling<StatementImpl<'_>>>, Error>

Asynchronous sibling of Self::execute. Uses polling mode to be asynchronous. sleep does govern the behaviour of polling, by waiting for the future in between polling. Sleep should not be implemented using a sleep which blocks the system thread, but rather utilize the methods provided by your async runtime. E.g.:

use odbc_api::{Connection, IntoParameter, Error};
use std::time::Duration;

async fn insert_post<'a>(
    connection: &'a Connection<'a>,
    user: &str,
    post: &str,
) -> Result<(), Error> {
    // Poll every 50 ms.
    let sleep = || tokio::time::sleep(Duration::from_millis(50));
    let sql = "INSERT INTO POSTS (user, post) VALUES (?, ?)";
    // Execute query using ODBC polling method
    let params = (&user.into_parameter(), &post.into_parameter());
    connection.execute_polling(&sql, params, sleep).await?;
    Ok(())
}
source

pub fn prepare(&self, query: &str) -> Result<Prepared<StatementImpl<'_>>, Error>

Prepares an SQL statement. This is recommended for repeated execution of similar queries.

Should your use case require you to execute the same query several times with different parameters, prepared queries are the way to go. These give the database a chance to cache the access plan associated with your SQL statement. It is not unlike compiling your program once and executing it several times.

use odbc_api::{Connection, Error, IntoParameter};
use std::io::{self, stdin, Read};

fn interactive(conn: &Connection) -> io::Result<()>{
    let mut prepared = conn.prepare("SELECT * FROM Movies WHERE title=?;").unwrap();
    let mut title = String::new();
    stdin().read_line(&mut title)?;
    while !title.is_empty() {
        match prepared.execute(&title.as_str().into_parameter()) {
            Err(e) => println!("{}", e),
            // Most drivers would return a result set even if no Movie with the title is found,
            // the result set would just be empty. Well, most drivers.
            Ok(None) => println!("No result set generated."),
            Ok(Some(cursor)) => {
                // ...print cursor contents...
            }
        }
        stdin().read_line(&mut title)?;
    }
    Ok(())
}
Parameters
  • query: The text representation of the SQL statement. E.g. “SELECT * FROM my_table;”. ? may be used as a placeholder in the statement text, to be replaced with parameters during execution.
source

pub fn preallocate(&self) -> Result<Preallocated<'_>, Error>

Allocates an SQL statement handle. This is recommended if you want to sequentially execute different queries over the same connection, as you avoid the overhead of allocating a statement handle for each query.

Should you want to repeatedly execute the same query with different parameters try Self::prepare instead.

Example
use odbc_api::{Connection, Error};
use std::io::{self, stdin, Read};

fn interactive(conn: &Connection) -> io::Result<()>{
    let mut statement = conn.preallocate().unwrap();
    let mut query = String::new();
    stdin().read_line(&mut query)?;
    while !query.is_empty() {
        match statement.execute(&query, ()) {
            Err(e) => println!("{}", e),
            Ok(None) => println!("No results set generated."),
            Ok(Some(cursor)) => {
                // ...print cursor contents...
            },
        }
        stdin().read_line(&mut query)?;
    }
    Ok(())
}
source

pub fn set_autocommit(&self, enabled: bool) -> Result<(), Error>

Specify the transaction mode. By default, ODBC transactions are in auto-commit mode. Switching from manual-commit mode to auto-commit mode automatically commits any open transaction on the connection. There is no open or begin transaction method. Each statement execution automatically starts a new transaction or adds to the existing one.

In manual commit mode you can use Connection::commit or Connection::rollback. Keep in mind, that even SELECT statements can open new transactions. This library will rollback open transactions if a connection goes out of SCOPE. This however will log an error, since the transaction state is only discovered during a failed disconnect. It is preferable that the application makes sure all transactions are closed if in manual commit mode.

source

pub fn commit(&self) -> Result<(), Error>

To commit a transaction in manual-commit mode.

source

pub fn rollback(&self) -> Result<(), Error>

To rollback a transaction in manual-commit mode.

source

pub fn is_dead(&self) -> Result<bool, Error>

Indicates the state of the connection. If true the connection has been lost. If false, the connection is still active.

source

pub fn database_management_system_name(&self) -> Result<String, Error>

Get the name of the database management system used by the connection.

source

pub fn max_catalog_name_len(&self) -> Result<u16, Error>

Maximum length of catalog names.

source

pub fn max_schema_name_len(&self) -> Result<u16, Error>

Maximum length of schema names.

source

pub fn max_table_name_len(&self) -> Result<u16, Error>

Maximum length of table names.

source

pub fn max_column_name_len(&self) -> Result<u16, Error>

Maximum length of column names.

source

pub fn current_catalog(&self) -> Result<String, Error>

Get the name of the current catalog being used by the connection.

source

pub fn columns( &self, catalog_name: &str, schema_name: &str, table_name: &str, column_name: &str ) -> Result<CursorImpl<StatementImpl<'_>>, Error>

A cursor describing columns of all tables matching the patterns. Patterns support as placeholder % for multiple characters or _ for a single character. Use \ to escape.The returned cursor has the columns: TABLE_CAT, TABLE_SCHEM, TABLE_NAME, COLUMN_NAME, DATA_TYPE, TYPE_NAME, COLUMN_SIZE, BUFFER_LENGTH, DECIMAL_DIGITS, NUM_PREC_RADIX, NULLABLE, REMARKS, COLUMN_DEF, SQL_DATA_TYPE, SQL_DATETIME_SUB, CHAR_OCTET_LENGTH, ORDINAL_POSITION, IS_NULLABLE.

In addition to that there may be a number of columns specific to the data source.

source

pub fn tables( &self, catalog_name: &str, schema_name: &str, table_name: &str, table_type: &str ) -> Result<CursorImpl<StatementImpl<'_>>, Error>

List tables, schemas, views and catalogs of a datasource.

Parameters
  • catalog_name: Filter result by catalog name. Accept search patterns. Use % to match any number of characters. Use _ to match exactly on character. Use \ to escape characeters.
  • schema_name: Filter result by schema. Accepts patterns in the same way as catalog_name.
  • table_name: Filter result by table. Accepts patterns in the same way as catalog_name.
  • table_type: Filters results by table type. E.g: ‘TABLE’, ‘VIEW’. This argument accepts a comma separeted list of table types. Omit it to not filter the result by table type at all.
Example
use odbc_api::{Connection, Cursor, Error, ResultSetMetadata, buffers::TextRowSet};

fn print_all_tables(conn: &Connection<'_>) -> Result<(), Error> {
    // Set all filters to an empty string, to really print all tables
    let mut cursor = conn.tables("", "", "", "")?;

    // The column are gonna be TABLE_CAT,TABLE_SCHEM,TABLE_NAME,TABLE_TYPE,REMARKS, but may
    // also contain additional driver specific columns.
    for (index, name) in cursor.column_names()?.enumerate() {
        if index != 0 {
            print!(",")
        }
        print!("{}", name?);
    }

    let batch_size = 100;
    let mut buffer = TextRowSet::for_cursor(batch_size, &mut cursor, Some(4096))?;
    let mut row_set_cursor = cursor.bind_buffer(&mut buffer)?;

    while let Some(row_set) = row_set_cursor.fetch()? {
        for row_index in 0..row_set.num_rows() {
            if row_index != 0 {
                print!("\n");
            }
            for col_index in 0..row_set.num_cols() {
                if col_index != 0 {
                    print!(",");
                }
                let value = row_set
                    .at_as_str(col_index, row_index)
                    .unwrap()
                    .unwrap_or("NULL");
                print!("{}", value);
            }
        }
    }

    Ok(())
}
source

pub fn foreign_keys( &self, pk_catalog_name: &str, pk_schema_name: &str, pk_table_name: &str, fk_catalog_name: &str, fk_schema_name: &str, fk_table_name: &str ) -> Result<CursorImpl<StatementImpl<'_>>, Error>

This can be used to retrieve either a list of foreign keys in the specified table or a list of foreign keys in other table that refer to the primary key of the specified table.

See: https://learn.microsoft.com/en-us/sql/odbc/reference/syntax/sqlforeignkeys-function

source

pub fn columns_buffer_descs( &self, type_name_max_len: usize, remarks_max_len: usize, column_default_max_len: usize ) -> Result<Vec<BufferDesc>, Error>

The buffer descriptions for all standard buffers (not including extensions) returned in the columns query (e.g. Connection::columns).

Arguments
  • type_name_max_len - The maximum expected length of type names.
  • remarks_max_len - The maximum expected length of remarks.
  • column_default_max_len - The maximum expected length of column defaults.

Trait Implementations§

source§

impl AsMut<Connection<'static>> for ODBCConnection

source§

fn as_mut(&mut self) -> &mut Connection<'static>

Converts this type into a mutable reference of the (usually inferred) input type.
source§

impl AsRef<Connection<'static>> for ODBCConnection

source§

fn as_ref(&self) -> &Connection<'static>

Converts this type into a shared reference of the (usually inferred) input type.
source§

impl Deref for ODBCConnection

§

type Target = Connection<'static>

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl DerefMut for ODBCConnection

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl Drop for ODBCConnection

source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for Twhere T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for Twhere T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for Twhere T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for Twhere U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T, U> TryFrom<U> for Twhere U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for Twhere U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.