这段代码
extern crate mysql;
use mysql::*;
fn main () {
let mut conn = Conn::new("mysql://root:password@127.0.0.1:3306/mydb?prefer_socket=false").unwrap();
let _q1 = conn.prepare("some query").unwrap();
let _q2 = conn.prepare("some query 2").unwrap();
}
产生错误:
error[E0499]: cannot borrow ``conn`` as mutable more than once at a time
--> src\bin\test.rs:8:12
|
7 | let _q1 = conn.prepare("some query").unwrap();
| ---- first mutable borrow occurs here
8 | let _q2 = conn.prepare("some query 2").unwrap();
| ^^^^ second mutable borrow occurs here
9 | }
| - first borrow ends here
我想第一次借用到第 9 行是因为 conn.prepare(...).unwrap()
的结果是 Stmt
和 Stmt
声明为
pub struct Stmt<'a> {
stmt: InnerStmt,
conn: ConnRef<'a>,
}
和ConnRef
被声明为
enum ConnRef<'a> {
ViaConnRef(&'a mut Conn), // It keeps mutable borrow as long as lifetime of connection?
ViaPooledConn(pool::PooledConn),
}
所以 _q1
保持可变借用直到 conn
结束。
如何在不产生编译时错误的情况下创建多个准备好的语句?
最佳答案
Stmt will borrow Conn until the end of its scope.
有一个Github issue这建议使用 prep_exec , 声称:
Overhead is negligible because of fast xxhash based statements cache.
关于mysql - 如何从一个 mysql::Conn 创建多个准备好的语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49369327/