0

我正在寻找通过我的 SQL 字符串绑定数据:

#[derive(Debug, sqlx::FromRow)]
struct CurrencyExchangeRateBdd {
    currency_exchange_rate_id: i64,
    from_currency: String,
    to_currency: String,
    rate_date: Date,
    rate: f64,
    creation_date: OffsetDateTime,
    rate_down: Option<f64>,
    rate_up: Option<f64>,
}

async fn get_data(date: &String) -> Result<Vec<CurrencyExchangeRateBdd>, sqlx::Error> {
    let pool = PgPoolOptions::new()
        .max_connections(5)
        .connect("postgres")
        .await?;

    let row = sqlx::query_as!(
        CurrencyExchangeRateBdd,
        "SELECT * FROM currency_exchange_rate WHERE rate_date = ?"
    )
    .bind(date)
    .fetch_all(&pool)
    .await;

    row
}

我收到此错误:

error: error returned from database: syntax error at end of input
  --> src/main.rs:50:15
   |
50 |     let row = sqlx::query_as!(CurrencyExchangeRateBdd,"SELECT * FROM currency_exchange_rate WHERE rate_date = ?")
   |               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   |
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

我努力了:

let row = sqlx::query_as!(CurrencyExchangeRateBdd, "SELECT * FROM currency_exchange_rate WHERE rate_date = ?", date)

$@而不是?。我和文档一样。

我该如何解决这个错误?

4

1 回答 1

2

正确的语法是:

let row = sqlx::query_as!(
    CurrencyExchangeRateBdd,
    "SELECT * FROM currency_exchange_rate WHERE rate_date = $1"
)

Postgres 使用标识符$1,$2等来指示准备好的语句中的参数。请参阅文档

sqlx的自述文件中的第一个示例还显示了 Postgres 参数的正确使用。

于 2021-07-13T14:47:31.983 回答