prepared_query/
prepared_query.rs1extern crate odbc_safe;
3use odbc_safe::*;
4use std::str::from_utf8;
5
6fn main() {
7
8 let env = Environment::new().unwrap();
9 let env = env.declare_version_3().unwrap();
10 let conn = connect(&env);
11 let mut stmt = prepare_query(&conn);
12 for &year in [1968, 1993].iter() {
13 let result_set = execute_query(stmt, year);
14 stmt = print_fields(result_set);
15 println!("");
16 }
17}
18
19fn connect<V>(env: &Environment<V>) -> Connection<impl AutocommitMode>
20where
21 V: Version,
22{
23 let conn = DataSource::with_parent(env).unwrap();
24 conn.connect("TestDataSource", "", "").unwrap()
25}
26
27fn prepare_query<'a, AC: AutocommitMode>(conn: &'a Connection<AC>) -> Statement<'a, 'a, 'a, NoCursor, Prepared> {
28 let stmt = Statement::with_parent(conn).unwrap();
29 stmt.prepare("SELECT TITLE FROM MOVIES WHERE YEAR = ?")
30 .unwrap()
31}
32
33fn execute_query<'a>(
34 stmt: Statement<'a, 'a, 'a, NoCursor, Prepared>,
35 year: i32,
36) -> ResultSet<'a, 'a, 'a, Prepared> {
37 let stmt = stmt.bind_input_parameter(1, DataType::Integer, &year, None)
38 .unwrap();
39 let stmt = match stmt.execute() {
40 ReturnOption::Success(s) |
41 ReturnOption::Info(s) => s,
42 ReturnOption::NoData(_) |
43 ReturnOption::Error(_) => panic!("No Result Set"),
44 };
45 stmt.reset_parameters()
46}
47
48fn print_fields<'a>(
49 result_set: ResultSet<'a, 'a, 'a, Prepared>,
50) -> Statement<'a, 'a, 'a, NoCursor, Prepared> {
51 let mut buffer = [0u8; 512];
52 let mut cursor = match result_set.fetch() {
53 ReturnOption::Success(r) |
54 ReturnOption::Info(r) => r,
55 ReturnOption::NoData(r) |
56 ReturnOption::Error(r) => return r,
57 };
58 loop {
59 match cursor.get_data(1, &mut buffer as &mut [u8]) {
60 ReturnOption::Success(ind) |
61 ReturnOption::Info(ind) => {
62 match ind {
63 Indicator::NoTotal => panic!("No Total"),
64 Indicator::Null => println!("NULL"),
65 Indicator::Length(l) => {
66 print!("{}", from_utf8(&buffer[0..l as usize]).unwrap());
67 }
68 }
69 }
70 ReturnOption::NoData(_) |
71 ReturnOption::Error(_) => panic!("No Field Data"),
72 }
73 cursor = match cursor.fetch() {
74 ReturnOption::Success(r) |
75 ReturnOption::Info(r) => r,
76 ReturnOption::NoData(r) |
77 ReturnOption::Error(r) => break r,
78 };
79 println!("");
80 }
81}