我尝试使用 prep_exec
与 params!
类似于 Conn
示例中的宏,还有 prepare
然后是 execute
来自 Stmt
.
这个函数有效:
pub fn get(DB: Pool, name: &str) -> Option<Settings> {
let mut ret: Option<Settings> = None;
let mut stmt = DB.prepare("SELECT * FROM settings").unwrap();
for row in stmt.execute().unwrap() {
let mut row = row.unwrap();
ret = Some(Settings {
id: row.take("id").unwrap(),
host: row.take("host"),
name: row.take("name").unwrap(),
value: row.take("value"),
});
break;
}
ret
}
但这不起作用,参数没有被替换:
pub fn get(DB: Pool, name: &str) -> Option<Settings> {
let mut ret: Option<Settings> = None;
let mut stmt = DB.prepare("SELECT * FROM settings WHERE name=?").unwrap();
for row in stmt.execute((name)).unwrap() {
let mut row = row.unwrap();
ret = Some(Settings {
id: row.take("id").unwrap(),
host: row.take("host"),
name: row.take("name").unwrap(),
value: row.take("value"),
});
break;
}
ret
}
错误是
thread 'main' panicked at 'called
Result::unwrap()
on anErr
value: MySqlError { ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' WHERE name=?' at line 1 }'
最佳答案
直接来自 documentation you linked .
let mut stmt1 = pool.prepare("SELECT ?").unwrap();
// just do not forget about trailing comma in case of arity = 1
for row in stmt1.execute((42,)).unwrap() {
let cell = from_row::<u8>(row.unwrap());
assert_eq!(cell, 42u8);
}
如果只有一个参数,请确保在 execute
中有尾随逗号。
关于mysql - 使用 mysql crate 时无法执行 MySQL 准备语句;参数未被替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40600826/