首页 > 解决方案 > 与 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"] } 

标签: postgresqlrust

解决方案


令我惊讶的是,这里是修复:

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/


推荐阅读