Struct odbc_api::Connection
source · [−]pub struct Connection<'c> { /* private fields */ }
Expand description
The connection handle references storage of all information about the connection to the data source, including status, transaction state, and error information.
Implementations
sourceimpl<'c> Connection<'c>
impl<'c> Connection<'c>
sourcepub fn into_sys(self) -> HDbc
pub fn into_sys(self) -> HDbc
Transfers ownership of the handle to this open connection to the raw ODBC pointer.
sourcepub fn into_handle(self) -> Connection<'c>
pub fn into_handle(self) -> Connection<'c>
Transfer ownership of this open connection to a wrapper around the raw ODBC pointer. The wrapper allows you to call ODBC functions on the handle, but doesn’t care if the connection is in the right state.
You should not have a need to call this method if your usecase is covered by this library, but, in case it is not, this may help you to break out of the type structure which might be to rigid for you, while simultaniously abondoning its safeguards.
sourcepub fn execute(
&self,
query: &str,
params: impl ParameterRefCollection
) -> Result<Option<CursorImpl<StatementImpl<'_>>>, Error>
pub fn execute(
&self,
query: &str,
params: impl ParameterRefCollection
) -> 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 thecrate::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;
let env = Environment::new()?;
let mut conn = env.connect("YourDatabase", "SA", "My@Test@Password1")?;
if let Some(cursor) = conn.execute("SELECT year, name FROM Birthdays;", ())? {
// Use cursor to process query results.
}
sourcepub fn into_cursor(
self,
query: &str,
params: impl ParameterRefCollection
) -> Result<Option<CursorImpl<StatementConnection<'c>>>, Error>
pub fn into_cursor(
self,
query: &str,
params: impl ParameterRefCollection
) -> Result<Option<CursorImpl<StatementConnection<'c>>>, Error>
In some use cases there you only execute a single statement, or the time to open a connection does not matter users may wish to choose to not keep a connection alive seperatly from the cursor, in order to have an easier time withe the borrow checker.
use lazy_static::lazy_static;
use odbc_api::{Environment, Error, Cursor};
lazy_static! {
static ref ENV: Environment = unsafe { Environment::new().unwrap() };
}
const CONNECTION_STRING: &str =
"Driver={ODBC Driver 17 for SQL Server};\
Server=localhost;UID=SA;\
PWD=My@Test@Password1;";
fn execute_query(query: &str) -> Result<Option<impl Cursor>, Error> {
let conn = ENV.connect_with_connection_string(CONNECTION_STRING)?;
// connect.execute(&query, ()) // Compiler error: Would return local ref to `conn`.
conn.into_cursor(&query, ())
}
sourcepub fn prepare(&self, query: &str) -> Result<Prepared<'_>, Error>
pub fn prepare(&self, query: &str) -> Result<Prepared<'_>, Error>
Prepares an SQL statement. This is recommended for repeated execution of similar queries.
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.
sourcepub fn preallocate(&self) -> Result<Preallocated<'_>, Error>
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(())
}
sourcepub fn set_autocommit(&self, enabled: bool) -> Result<(), Error>
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.
sourcepub fn is_dead(&self) -> Result<bool, Error>
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.
sourcepub unsafe fn promote_to_send(self) -> Send<Self>
pub unsafe fn promote_to_send(self) -> Send<Self>
Allows sending this connection to different threads. This Connection will still be only be used by one thread at a time, but it may be a different thread each time.
Example
use std::thread;
use lazy_static::lazy_static;
use odbc_api::Environment;
lazy_static! {
static ref ENV: Environment = unsafe { Environment::new().unwrap() };
}
const MSSQL: &str =
"Driver={ODBC Driver 17 for SQL Server};\
Server=localhost;\
UID=SA;\
PWD=My@Test@Password1;\
";
let conn = ENV.connect_with_connection_string("MSSQL").unwrap();
let conn = unsafe { conn.promote_to_send() };
let handle = thread::spawn(move || {
if let Some(cursor) = conn.execute("SELECT title FROM Movies ORDER BY year",())? {
// Use cursor to process results
}
Ok::<(), odbc_api::Error>(())
});
handle.join().unwrap()?;
Safety
According to the ODBC standard this should be safe. By calling this function you express your trust in the implementation of the ODBC driver your application is using.
See: https://docs.microsoft.com/en-us/sql/odbc/reference/develop-app/multithreading?view=sql-server-ver15
This function may be removed in future versions of this crate and connections would be
Send
out of the Box. This will require sufficient testing in which a wide variety of
database drivers prove to be thread safe. For now this API tries to error on the side of
caution, and leaves the amount of trust you want to put in the driver implementation to the
user. I have seen this go wrong in the past, but time certainly improved the situation. At
one point this will be cargo cult and Connection can be Send
by default (hopefully).
Note to users of unixodbc
: You may configure the threading level to make unixodbc
synchronize access to the driver (and thereby making them thread safe if they are not thread
safe by themself. This may however hurt your performance if the driver would actually be
able to perform operations in parallel.
See: https://stackoverflow.com/questions/4207458/using-unixodbc-in-a-multithreaded-concurrent-setting
sourcepub fn database_management_system_name(&self) -> Result<String, Error>
pub fn database_management_system_name(&self) -> Result<String, Error>
Get the name of the database management system used by the connection.
sourcepub fn max_catalog_name_len(&self) -> Result<u16, Error>
pub fn max_catalog_name_len(&self) -> Result<u16, Error>
Maximum length of catalog names.
sourcepub fn max_schema_name_len(&self) -> Result<u16, Error>
pub fn max_schema_name_len(&self) -> Result<u16, Error>
Maximum length of schema names.
sourcepub fn max_table_name_len(&self) -> Result<u16, Error>
pub fn max_table_name_len(&self) -> Result<u16, Error>
Maximum length of table names.
sourcepub fn max_column_name_len(&self) -> Result<u16, Error>
pub fn max_column_name_len(&self) -> Result<u16, Error>
Maximum length of column names.
sourcepub fn current_catalog(&self) -> Result<String, Error>
pub fn current_catalog(&self) -> Result<String, Error>
Get the name of the current catalog being used by the connection.
sourcepub fn columns(
&self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
column_name: &str
) -> Result<CursorImpl<StatementImpl<'_>>, Error>
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.
sourcepub fn tables(
&self,
catalog_name: &str,
schema_name: &str,
table_name: &str,
table_type: &str
) -> Result<CursorImpl<StatementImpl<'_>>, Error>
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 ascatalog_name
.table_name
: Filter result by table. Accepts patterns in the same way ascatalog_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 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, &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(())
}
sourcepub fn columns_buffer_description(
&self,
type_name_max_len: usize,
remarks_max_len: usize,
column_default_max_len: usize
) -> Result<Vec<BufferDescription>, Error>
pub fn columns_buffer_description(
&self,
type_name_max_len: usize,
remarks_max_len: usize,
column_default_max_len: usize
) -> Result<Vec<BufferDescription>, 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
Auto Trait Implementations
impl<'c> RefUnwindSafe for Connection<'c>
impl<'c> !Send for Connection<'c>
impl<'c> !Sync for Connection<'c>
impl<'c> Unpin for Connection<'c>
impl<'c> UnwindSafe for Connection<'c>
Blanket Implementations
sourceimpl<T> BorrowMut<T> for T where
T: ?Sized,
impl<T> BorrowMut<T> for T where
T: ?Sized,
const: unstable · sourcefn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more