Expand description
A minimal safe interface to sqlite3’s basic API.
The basic sqlite3 API is discussed in the sqlite intro.
To go beyond that, use the (unsafe) ffi
module directly.
extern crate sqlite3;
use sqlite3::{
DatabaseConnection,
SqliteResult,
};
fn convenience_exec() -> SqliteResult<DatabaseConnection> {
let mut conn = try!(DatabaseConnection::in_memory());
try!(conn.exec("
create table items (
id integer,
description varchar(40),
price integer
)"));
Ok(conn)
}
fn typical_usage(conn: &mut DatabaseConnection) -> SqliteResult<String> {
{
let mut stmt = try!(conn.prepare(
"insert into items (id, description, price)
values (1, 'stuff', 10)"));
let mut results = stmt.execute();
match try!(results.step()) {
None => (),
Some(_) => panic!("row from insert?!")
};
}
assert_eq!(conn.changes(), 1);
assert_eq!(conn.last_insert_rowid(), 1);
{
let mut stmt = try!(conn.prepare(
"select * from items"));
let mut results = stmt.execute();
match results.step() {
Ok(Some(ref mut row1)) => {
let id = row1.column_int(0);
let desc_opt = row1.column_text(1).expect("desc_opt should be non-null");
let price = row1.column_int(2);
assert_eq!(id, 1);
assert_eq!(desc_opt, format!("stuff"));
assert_eq!(price, 10);
Ok(format!("row: {}, {}, {}", id, desc_opt, price))
},
Err(oops) => panic!(oops),
Ok(None) => panic!("where did our row go?")
}
}
}
pub fn main() {
match convenience_exec() {
Ok(ref mut db) => {
match typical_usage(db) {
Ok(txt) => println!("item: {}", txt),
Err(oops) => {
panic!("error: {:?} msg: {}", oops,
db.errmsg())
}
}
},
Err(oops) => panic!(oops)
}
}
The DatabaseConnection
and PreparedStatment
structures are
memory-safe versions of the sqlite3 connection and prepared
statement structures. A PreparedStatement
maintains mutable,
and hence exclusive, reference to the database connection.
Note the use of blocks avoid borrowing the connection more
than once at a time.
In addition:
-
ResultSet
represents, as a rust lifetime, all of the steps of one execution of a statement. (Ideally, it would be an Iterator overResultRow
s, but theIterator::next()
function has no lifetime parameter.) Use of mutable references ensures that its lifetime is subsumed by the statement lifetime. Its destructor resets the statement. -
ResultRow
is a lifetime for access to the columns of one row.
Re-exports§
pub use super::SqliteError;
pub use super::SqliteErrorCode;
pub use super::SqliteResult;
pub use super::ColumnType;
pub use super::ColumnType::SQLITE_NULL;
Structs§
- Database
Connection - A connection to a sqlite3 database.
- Prepared
Statement - A prepared statement.
- Result
Row - Access to columns of a row.
- Result
Set - Results of executing a
prepare()
d statement.
Enums§
Traits§
- Access
- Authorization to connect to database.
Functions§
- decode_
result - Decode SQLite result as
SqliteResult
. - str_
charstar - Convenience function to get a CString from a str