mysql - 如何从一个 mysql::Conn 创建多个准备好的语句?

标签 mysql rust

这段代码

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() 的结果是 StmtStmt 声明为

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 结束。

如何在不产生编译时错误的情况下创建多个准备好的语句?

最佳答案

documentation状态:

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/

相关文章:

rust - 特征类型和生命周期问题

php - 使用ajax将 session 变量插入数据库

MySQL 数据库 SQL 与 Excel 数据没有结果

rust - Rust 中的生命周期 : mut data borrowed

rust - 是否有可能具有比其自身尺寸更大的对齐方式?

rust - 如何将 number::Rational 转换为十进制数?

multithreading - 如何控制 Rust 中 2 个不同线程的打印顺序

php - 在mysql中从午夜减去时间

mysql - 如果表中已有记录,如何创建外键?

mysql - 为什么 sql 正确和运行它的内部机制?