postgresql - 与 postgres crate 的查询函数一起使用时,是否需要对 ilike 表达式中的“$1”参数进行转义?
问题描述
我正在使用 postgres 板条箱,它使用postgres::Connection
. 我根据ilike '%search_string%'
表达式中的字符串值查询表:
extern crate postgres;
use std::error::Error;
//DB Create queries
/*
CREATE TABLE TestTable (
Id SERIAL primary key,
_Text varchar(50000) NOT NULL
);
insert into TestTable (_Text) values ('test1');
insert into TestTable (_Text) values ('test1');
*/
fn main() -> Result<(), Box<dyn Error>> {
let conn = postgres::Connection::connect(
"postgres://postgres:postgres@localhost:5432/notes_server",
postgres::TlsMode::None,
)?;
let text = "test";
// //Does not work
// let query = &conn.query(
// "
// select * from TestTable where _text ilike '%$1%'
// ",
// &[&text],
// )?;
//Works fine
let query = &conn.query(
"
select * from TestTable where Id = $1
",
&[&1],
)?;
println!("Rows returned: {}", query.iter().count());
Ok(())
}
如果我取消注释//Does not work part
代码,我将收到以下错误:
thread 'main' panicked at 'expected 0 parameters but got 1'
它似乎无法识别表达式$1
中包含的参数。ilike
我试过转义单引号,但这并没有改变它。
唯一的依赖是:
postgres = { version = "0.15.2", features = ["with-chrono"] }
解决方案
令我惊讶的是,这里是修复:
let text = "%test%";
let query = &conn.query(
"
select * from TestTable where _text like $1
",&[&text],
)?;
显然 postgres 函数知道在这种情况下在字符串周围添加单引号。
我从这里发现了这一点:https ://www.reddit.com/r/rust/comments/8ltad7/horrible_quote_escaping_conundrum_any_ideas_on/
推荐阅读
- r - 如何从参考坐标中选择“N”公里内的坐标
- python - 将两个整数列相加,避免使用字符串和 Nan
- c - #包括“板.H”
- javascript - 将 slideToggle() 添加到函数中
- c# - 本地 SQL 的相对路径
- vb.net - SelectCommand 属性在调用 'Fill' 之前没有被初始化的问题
- reactjs - 我想使用 react-images 在模态轮播上添加一个“下载按钮,该按钮应该在模态弹出窗口中可用
- spring-boot - CompletableFuture 链中的程序化交易
- python - 如何通过跟随兄弟获得下一个元素?
- ios - 在单独的模块中定义的类型约束协议的问题