rust - 有没有一种方法可以在循环中使用odbc::Statement编写函数?

标签 rust

我有一个简单循环的工作示例(主要取自odbc crate 的示例):

use std::io;
use odbc::*;
use odbc_safe::AutocommitOn;
fn main(){
    let env = create_environment_v3().map_err(|e| e.unwrap()).unwrap();
    let conn = env.connect_with_connection_string(CONN_STRING).unwrap();
    let mut stmt = Statement::with_parent(&conn).unwrap();
    loop {
        let mut sql_text = String::new();
        println!("Please enter SQL statement string: ");
        io::stdin().read_line(&mut sql_text).unwrap();
        stmt = match stmt.exec_direct(&sql_text).unwrap() {
            Data(mut stmt) => {
                let cols = stmt.num_result_cols().unwrap();
                while let Some(mut cursor) = stmt.fetch().unwrap() {
                    for i in 1..(cols + 1) {
                        match cursor.get_data::<&str>(i as u16).unwrap() {
                            Some(val) => print!(" {}", val),
                            None => print!(" NULL"),
                        }
                    }
                    println!();
                }
                stmt.close_cursor().unwrap()
            }
            NoData(stmt) => {println!("Query executed, no data returned"); stmt}
        }
    }
}

我不想为每个查询创建新的Statements,因为我只能使用.close_cursor()。
我想将循环的主体提取为一个函数,如下所示:
fn exec_stmt(stmt: Statement<Allocated, NoResult, AutocommitOn>) {
    //loop's body here
}

但是我不能! .exec_direct()方法可变地消耗我的Statement并返回另一个。我尝试了不同的方法将Statement arg传递给函数(借用,RefCell等),但是在循环中使用时,它们都会失败。我仍然对Rust还是陌生的,所以很可能我只是不了解某些东西,或者.exec_direct的Statement消耗是否使它不可能?

最佳答案

没有很好的方法来移动然后通过参数返回值。最好复制.exec_direct所做的事情,并且仅将函数的返回类型也声明为语句。

用法如下所示:

let mut stmt = Statement::with_parent(&conn).unwrap();
loop {
    stmt = exec_stmt(stmnt);
}

并且您的功能签名将是:

fn exec_stmt(stmt: Statement<...>) -> Statement<...> {
  match stmt.exec_direct() {
    ...
  }
}

我可能不建议这样做,但是如果您真的想使其工作,可以使用Option.take()方法。
fn exec_stmt(some_stmt: &mut Option<Statement<...>>) {
   let stmt = some_stmt.take().unwrap();
   // do stuff ...
   some_stmt.replace(stmt);
}

关于rust - 有没有一种方法可以在循环中使用odbc::Statement编写函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62244922/

相关文章:

syntax - 元组、结构和元组结构需要在 Rust 中具有不一致的语法吗?

rust - 如果闭包捕获变量,如何将其作为函数参数传递

rust - 基于迭代器的代码与过程代码 : how to make the iterator-based algorithm faster?

rust - 了解 rust 借用和取消引用

python - 在解释器或编译器的上下文中,单元格是什么?

error-handling - 如何在 rust 中使用if else方法获取错误?

types - 如何 unwrap_or 到 String

rust - 将存储在 u32 数组中的大数转换为字节并返回

mongodb - 如何将actix_web Json存储到mongodb?

rust - 为什么 Vec::as_slice 和数组强制的生命周期检查不同?