我正在使用 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(())
}
Run Code Online (Sandbox Code Playgroud)
如果我取消注释//Does not work part代码,我将收到以下错误:
thread 'main' panicked at 'expected 0 parameters but got 1'
Run Code Online (Sandbox Code Playgroud)
它似乎无法识别$1表达式中包含的参数ilike。我尝试转义单引号,但这并没有改变它。
唯一的依赖项是:
postgres = { version = "0.15.2", features = ["with-chrono"] }
Run Code Online (Sandbox Code Playgroud)
令我惊讶的是,修复方法如下:
let text = "%test%";
let query = &conn.query(
"
select * from TestTable where _text like $1
",&[&text],
)?;
Run Code Online (Sandbox Code Playgroud)
显然,postgres 函数知道在这种情况下在字符串周围添加单引号。
我从这里发现了这一点:https://www.reddit.com/r/rust/comments/8ltad7/horrible_quote_escaping_conundrum_any_ideas_on/
| 归档时间: |
|
| 查看次数: |
1406 次 |
| 最近记录: |