1

I need to pass several parameters into the tokio_postgres::query Statement. How can I properly do this?

The way I do it below doesn't work, what gets passed into the SQL database is the unconverted $2, instead of the date 2021-04-06.

use tokio_postgres::{Error, NoTls};

#[tokio::main]
async fn main() -> Result<(), Error> {
    let (client, connection) = tokio_postgres::connect(
        "dbname=database user=admin password=postgres host=db port=5432",
        NoTls,
    )
    .await?;


    // Spawn the connector in a separate async task
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: {}", e);
        }
    });

    // How do I pass several parameters correctly here?
    client
        .query(
            "INSERT INTO table_name (url, date_added) \
                    VALUES ('$1', '$2');",
            &[&url, &"2021-04-06"],
        )
        .await?;
}
  • 1
    Don't quote your parameters: `INSERT INTO table_name (url, date_added) VALUES ($1, $2);`. – eggyal Mar 06 '21 at 14:48
  • Now it complains about this: `Error: Error(SqlError(Error { kind: ToSql(1), cause: Some(WrongType { postgres: Date, rust: "&str" }) }), State { next_error: None, backtrace: InternalBacktrace { backtrace: None } })`. How do I pass it a Date inside Rust???? – Andriy Sultanov Mar 06 '21 at 17:33
  • Okay, I figured out that `chrono::NaiveDate` works as Date for tokio-postgres :) – Andriy Sultanov Mar 06 '21 at 18:10

0 Answers0