Rust SQLX iLike“%$1%”-按子字符串选择

v8wbuo2f  于 2023-04-30  发布在  其他
关注(0)|答案(1)|浏览(136)

你好!你能告诉我怎么做吗?
db:Postrgresql
iLike '%$1%' -在rust sqlx crate中无法正常工作,无法在库中找到工作解决方案

const QUERY_SELECT_COUNTRY_BY_COUNTRY_NAME: &str = "SELECT * FROM dictionary_country WHERE name_en iLike '%$1%' ";

pub async fn get_country_list_by_country_name(tx: &mut Transaction<'static, Postgres>, country_name: &str) -> Result<Vec<CountryModel>, AppGenericError> {
    info!("get_country_list_by_country_name country_name = {}", &country_name);

    match sqlx::query(QUERY_SELECT_COUNTRY_BY_COUNTRY_NAME)
        .bind("Rus")
        .map(|row: PgRow| CountryModel::from(row))
        .fetch_all(&mut *tx)
        .await {
        Ok(data) => Ok(data),
        Err(err) => Err(AppRepositoryError::general_error(err.to_string()))
    }
}

期望看到1个结果行
更新:工作溶液

const QUERY_SELECT_COUNTRY_BY_COUNTRY_NAME: &str = "SELECT * FROM dictionary_country WHERE name_en iLike $1 ";

pub async fn get_country_list_by_country_name(tx: &mut Transaction<'static, Postgres>, country_name: &str) -> Result<Vec<CountryModel>, AppGenericError> {
    info!("get_country_list_by_country_name country_name = {}", &country_name);

    match sqlx::query(QUERY_SELECT_COUNTRY_BY_COUNTRY_NAME)
        .bind(format!("%{}%", country_name))
        .map(|row: PgRow| CountryModel::from(row))
        .fetch_all(&mut *tx)
        .await {
        Ok(data) => Ok(data),
        Err(err) => Err(AppRepositoryError::general_error(err.to_string()))
    }
}
s6fujrry

s6fujrry1#

你需要把 Package %放在bind中:

const QUERY_SELECT_COUNTRY_BY_COUNTRY_NAME: &str = "SELECT * FROM dictionary_country WHERE name_en iLike $1 ";

pub async fn get_country_list_by_country_name(tx: &mut Transaction<'static, Postgres>, country_name: &str) -> Result<Vec<CountryModel>, AppGenericError> {
    info!("get_country_list_by_country_name country_name = {}", &country_name);

    match sqlx::query(QUERY_SELECT_COUNTRY_BY_COUNTRY_NAME)
        .bind(format!("%{}%", "Rus"))
        .map(|row: PgRow| CountryModel::from(row))
        .fetch_all(&mut *tx)
        .await {
        Ok(data) => Ok(data),
        Err(err) => Err(AppRepositoryError::general_error(err.to_string()))
    }
}

相关问题