CachedStatement

Struct CachedStatement 

Source
pub struct CachedStatement<'conn> { /* private fields */ }
Expand description

Cacheable statement.

Statement will return automatically to the cache by default. If you want the statement to be discarded, call discard() on it.

Implementations§

Source§

impl CachedStatement<'_>

Source

pub fn discard(self)

Discard the statement, preventing it from being returned to its Connection’s collection of cached statements.

Methods from Deref<Target = Statement<'conn>>§

Source

pub fn column_names(&self) -> Vec<&str>

Get all the column names in the result set of the prepared statement.

Source

pub fn column_count(&self) -> usize

Return the number of columns in the result set returned by the prepared statement.

Source

pub fn column_name(&self, col: usize) -> Result<&str>

Returns the name assigned to a particular column in the result set returned by the prepared statement.

§Failure

Returns an Error::InvalidColumnIndex if idx is outside the valid column range for this row.

Panics when column name is not valid UTF-8.

Source

pub fn column_index(&self, name: &str) -> Result<usize>

Returns the column index in the result set for a given column name.

If there is no AS clause then the name of the column is unspecified and may change from one release of SQLite to the next.

§Failure

Will return an Error::InvalidColumnName when there is no column with the specified name.

Source

pub fn columns(&self) -> Vec<Column<'_>>

Returns a slice describing the columns of the result of the query.

Source

pub fn execute<P: Params>(&mut self, params: P) -> Result<usize>

Execute the prepared statement.

On success, returns the number of rows that were changed or inserted or deleted (via sqlite3_changes).

§Example
§Use with positional parameters
fn update_rows(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("UPDATE foo SET bar = 'baz' WHERE qux = ?")?;
    // The `rusqlite::params!` macro is mostly useful when the parameters do not
    // all have the same type, or if there are more than 32 parameters
    // at once.
    stmt.execute(params![1i32])?;
    // However, it's not required, many cases are fine as:
    stmt.execute(&[&2i32])?;
    // Or even:
    stmt.execute([2i32])?;
    Ok(())
}
§Use with named parameters
fn insert(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("INSERT INTO test (key, value) VALUES (:key, :value)")?;
    // The `rusqlite::named_params!` macro (like `params!`) is useful for heterogeneous
    // sets of parameters (where all parameters are not the same type), or for queries
    // with many (more than 32) statically known parameters.
    stmt.execute(named_params!{ ":key": "one", ":val": 2 })?;
    // However, named parameters can also be passed like:
    stmt.execute(&[(":key", "three"), (":val", "four")])?;
    // Or even: (note that a &T is required for the value type, currently)
    stmt.execute(&[(":key", &100), (":val", &200)])?;
    Ok(())
}
§Use without parameters
fn delete_all(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("DELETE FROM users")?;
    stmt.execute([])?;
    Ok(())
}
§Failure

Will return Err if binding parameters fails, the executed statement returns rows (in which case query should be used instead), or the underlying SQLite call fails.

Source

pub fn execute_named(&mut self, params: &[(&str, &dyn ToSql)]) -> Result<usize>

👎Deprecated: You can use execute with named params now.

Execute the prepared statement with named parameter(s).

Note: This function is deprecated in favor of Statement::execute, which can now take named parameters directly.

If any parameters that were in the prepared statement are not included in params, they will continue to use the most-recently bound value from a previous call to execute_named, or NULL if they have never been bound.

On success, returns the number of rows that were changed or inserted or deleted (via sqlite3_changes).

§Failure

Will return Err if binding parameters fails, the executed statement returns rows (in which case query should be used instead), or the underlying SQLite call fails.

Source

pub fn insert<P: Params>(&mut self, params: P) -> Result<i64>

Execute an INSERT and return the ROWID.

§Note

This function is a convenience wrapper around execute() intended for queries that insert a single item. It is possible to misuse this function in a way that it cannot detect, such as by calling it on a statement which updates a single item rather than inserting one. Please don’t do that.

§Failure

Will return Err if no row is inserted or many rows are inserted.

Source

pub fn query<P: Params>(&mut self, params: P) -> Result<Rows<'_>>

Execute the prepared statement, returning a handle to the resulting rows.

Due to lifetime restricts, the rows handle returned by query does not implement the Iterator trait. Consider using query_map or query_and_then instead, which do.

§Example
§Use without parameters
fn get_names(conn: &Connection) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT name FROM people")?;
    let mut rows = stmt.query([])?;

    let mut names = Vec::new();
    while let Some(row) = rows.next()? {
        names.push(row.get(0)?);
    }

    Ok(names)
}
§Use with positional parameters
fn query(conn: &Connection, name: &str) -> Result<()> {
    let mut stmt = conn.prepare("SELECT * FROM test where name = ?")?;
    let mut rows = stmt.query(rusqlite::params![name])?;
    while let Some(row) = rows.next()? {
        // ...
    }
    Ok(())
}

Or, equivalently (but without the [params!] macro).

fn query(conn: &Connection, name: &str) -> Result<()> {
    let mut stmt = conn.prepare("SELECT * FROM test where name = ?")?;
    let mut rows = stmt.query(&[name])?;
    while let Some(row) = rows.next()? {
        // ...
    }
    Ok(())
}
§Use with named parameters
fn query(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("SELECT * FROM test where name = :name")?;
    let mut rows = stmt.query(&[(":name", &"one")])?;
    while let Some(row) = rows.next()? {
        // ...
    }
    Ok(())
}

Note, the named_params! macro is provided for syntactic convenience, and so the above example could also be written as:

fn query(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("SELECT * FROM test where name = :name")?;
    let mut rows = stmt.query(named_params!{ ":name": "one" })?;
    while let Some(row) = rows.next()? {
        // ...
    }
    Ok(())
}
§Failure

Will return Err if binding parameters fails.

Source

pub fn query_named(&mut self, params: &[(&str, &dyn ToSql)]) -> Result<Rows<'_>>

👎Deprecated: You can use query with named params now.

Execute the prepared statement with named parameter(s), returning a handle for the resulting rows.

Note: This function is deprecated in favor of Statement::query, which can now take named parameters directly.

If any parameters that were in the prepared statement are not included in params, they will continue to use the most-recently bound value from a previous call to query_named, or NULL if they have never been bound.

§Failure

Will return Err if binding parameters fails.

Source

pub fn query_map<T, P, F>( &mut self, params: P, f: F, ) -> Result<MappedRows<'_, F>>
where P: Params, F: FnMut(&Row<'_>) -> Result<T>,

Executes the prepared statement and maps a function over the resulting rows, returning an iterator over the mapped function results.

f is used to tranform the streaming iterator into a standard iterator.

This is equivalent to stmt.query(params)?.mapped(f).

§Example
§Use with positional params
fn get_names(conn: &Connection) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT name FROM people")?;
    let rows = stmt.query_map([], |row| row.get(0))?;

    let mut names = Vec::new();
    for name_result in rows {
        names.push(name_result?);
    }

    Ok(names)
}
§Use with named params
fn get_names(conn: &Connection) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
    let rows = stmt.query_map(&[(":id", &"one")], |row| row.get(0))?;

    let mut names = Vec::new();
    for name_result in rows {
        names.push(name_result?);
    }

    Ok(names)
}
§Failure

Will return Err if binding parameters fails.

Source

pub fn query_map_named<T, F>( &mut self, params: &[(&str, &dyn ToSql)], f: F, ) -> Result<MappedRows<'_, F>>
where F: FnMut(&Row<'_>) -> Result<T>,

👎Deprecated: You can use query_map with named params now.

Execute the prepared statement with named parameter(s), returning an iterator over the result of calling the mapping function over the query’s rows.

Note: This function is deprecated in favor of Statement::query_map, which can now take named parameters directly.

If any parameters that were in the prepared statement are not included in params, they will continue to use the most-recently bound value from a previous call to query_named, or NULL if they have never been bound.

f is used to tranform the streaming iterator into a standard iterator.

§Failure

Will return Err if binding parameters fails.

Source

pub fn query_and_then<T, E, P, F>( &mut self, params: P, f: F, ) -> Result<AndThenRows<'_, F>>
where P: Params, E: From<Error>, F: FnMut(&Row<'_>) -> Result<T, E>,

Executes the prepared statement and maps a function over the resulting rows, where the function returns a Result with Error type implementing std::convert::From<Error> (so errors can be unified).

This is equivalent to stmt.query(params)?.and_then(f).

§Example
§Use with named params
struct Person {
    name: String,
};

fn name_to_person(name: String) -> Result<Person> {
    // ... check for valid name
    Ok(Person { name: name })
}

fn get_names(conn: &Connection) -> Result<Vec<Person>> {
    let mut stmt = conn.prepare("SELECT name FROM people WHERE id = :id")?;
    let rows =
        stmt.query_and_then(&[(":id", &"one")], |row| name_to_person(row.get(0)?))?;

    let mut persons = Vec::new();
    for person_result in rows {
        persons.push(person_result?);
    }

    Ok(persons)
}
§Use with positional params
fn get_names(conn: &Connection) -> Result<Vec<String>> {
    let mut stmt = conn.prepare("SELECT name FROM people WHERE id = ?")?;
    let rows = stmt.query_and_then(&["one"], |row| row.get::<_, String>(0))?;

    let mut persons = Vec::new();
    for person_result in rows {
        persons.push(person_result?);
    }

    Ok(persons)
}
§Failure

Will return Err if binding parameters fails.

Source

pub fn query_and_then_named<T, E, F>( &mut self, params: &[(&str, &dyn ToSql)], f: F, ) -> Result<AndThenRows<'_, F>>
where E: From<Error>, F: FnMut(&Row<'_>) -> Result<T, E>,

👎Deprecated: You can use query_and_then with named params now.

Execute the prepared statement with named parameter(s), returning an iterator over the result of calling the mapping function over the query’s rows.

Note: This function is deprecated in favor of Statement::query_and_then, which can now take named parameters directly.

If any parameters that were in the prepared statement are not included in params, they will continue to use the most-recently bound value from a previous call to query_named, or NULL if they have never been bound.

§Failure

Will return Err if binding parameters fails.

Source

pub fn exists<P: Params>(&mut self, params: P) -> Result<bool>

Return true if a query in the SQL statement it executes returns one or more rows and false if the SQL returns an empty set.

Source

pub fn query_row<T, P, F>(&mut self, params: P, f: F) -> Result<T>
where P: Params, F: FnOnce(&Row<'_>) -> Result<T>,

Convenience method to execute a query that is expected to return a single row.

If the query returns more than one row, all rows except the first are ignored.

Returns Err(QueryReturnedNoRows) if no results are returned. If the query truly is optional, you can call .optional() on the result of this to get a Result<Option<T>> (requires that the trait rusqlite::OptionalExtension is imported).

§Failure

Will return Err if the underlying SQLite call fails.

Source

pub fn query_row_named<T, F>( &mut self, params: &[(&str, &dyn ToSql)], f: F, ) -> Result<T>
where F: FnOnce(&Row<'_>) -> Result<T>,

👎Deprecated: You can use query_row with named params now.

Convenience method to execute a query with named parameter(s) that is expected to return a single row.

Note: This function is deprecated in favor of Statement::query_and_then, which can now take named parameters directly.

If the query returns more than one row, all rows except the first are ignored.

Returns Err(QueryReturnedNoRows) if no results are returned. If the query truly is optional, you can call .optional() on the result of this to get a Result<Option<T>> (requires that the trait rusqlite::OptionalExtension is imported).

§Failure

Will return Err if sql cannot be converted to a C-compatible string or if the underlying SQLite call fails.

Source

pub fn parameter_index(&self, name: &str) -> Result<Option<usize>>

Return the (one-based) index of an SQL parameter given its name.

Note that the initial “:” or “$” or “@” or “?” used to specify the parameter is included as part of the name.

fn example(conn: &Connection) -> Result<()> {
    let stmt = conn.prepare("SELECT * FROM test WHERE name = :example")?;
    let index = stmt.parameter_index(":example")?;
    assert_eq!(index, Some(1));
    Ok(())
}
§Failure

Will return Err if name is invalid. Will return Ok(None) if the name is valid but not a bound parameter of this statement.

Source

pub fn parameter_count(&self) -> usize

Return the number of parameters that can be bound to this statement.

Source

pub fn raw_bind_parameter<T: ToSql>( &mut self, one_based_col_index: usize, param: T, ) -> Result<()>

Low level API to directly bind a parameter to a given index.

Note that the index is one-based, that is, the first parameter index is 1 and not 0. This is consistent with the SQLite API and the values given to parameters bound as ?NNN.

The valid values for one_based_col_index begin at 1, and end at Statement::parameter_count, inclusive.

§Caveats

This should not generally be used, but is available for special cases such as:

  • binding parameters where a gap exists.
  • binding named and positional parameters in the same query.
  • separating parameter binding from query execution.

Statements that have had their parameters bound this way should be queried or executed by Statement::raw_query or Statement::raw_execute. Other functions are not guaranteed to work.

§Example
fn query(conn: &Connection) -> Result<()> {
    let mut stmt = conn.prepare("SELECT * FROM test WHERE name = :name AND value > ?2")?;
    let name_index = stmt.parameter_index(":name")?.expect("No such parameter");
    stmt.raw_bind_parameter(name_index, "foo")?;
    stmt.raw_bind_parameter(2, 100)?;
    let mut rows = stmt.raw_query();
    while let Some(row) = rows.next()? {
        // ...
    }
    Ok(())
}
Source

pub fn raw_execute(&mut self) -> Result<usize>

Low level API to execute a statement given that all parameters were bound explicitly with the Statement::raw_bind_parameter API.

§Caveats

Any unbound parameters will have NULL as their value.

This should not generally be used outside of special cases, and functions in the Statement::execute family should be preferred.

§Failure

Will return Err if the executed statement returns rows (in which case query should be used instead), or the underlying SQLite call fails.

Source

pub fn raw_query(&mut self) -> Rows<'_>

Low level API to get Rows for this query given that all parameters were bound explicitly with the Statement::raw_bind_parameter API.

§Caveats

Any unbound parameters will have NULL as their value.

This should not generally be used outside of special cases, and functions in the Statement::query family should be preferred.

Note that if the SQL does not return results, Statement::raw_execute should be used instead.

Source

pub fn expanded_sql(&self) -> Option<String>

Returns a string containing the SQL text of prepared statement with bound parameters expanded.

Source

pub fn get_status(&self, status: StatementStatus) -> i32

Get the value for one of the status counters for this statement.

Source

pub fn reset_status(&self, status: StatementStatus) -> i32

Reset the value of one of the status counters for this statement, returning the value it had before resetting.

Trait Implementations§

Source§

impl<'conn> Deref for CachedStatement<'conn>

Source§

type Target = Statement<'conn>

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Statement<'conn>

Dereferences the value.
Source§

impl<'conn> DerefMut for CachedStatement<'conn>

Source§

fn deref_mut(&mut self) -> &mut Statement<'conn>

Mutably dereferences the value.
Source§

impl Drop for CachedStatement<'_>

Source§

fn drop(&mut self)

Executes the destructor for this type. Read more

Auto Trait Implementations§

§

impl<'conn> !Freeze for CachedStatement<'conn>

§

impl<'conn> !RefUnwindSafe for CachedStatement<'conn>

§

impl<'conn> !Send for CachedStatement<'conn>

§

impl<'conn> !Sync for CachedStatement<'conn>

§

impl<'conn> Unpin for CachedStatement<'conn>

§

impl<'conn> !UnwindSafe for CachedStatement<'conn>

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where 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 T
where 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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
Source§

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

Source§

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 T
where U: TryFrom<T>,

Source§

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.
Source§

impl<T> ErasedDestructor for T
where T: 'static,