tokio-postgres 和数据库查询

Mik*_*kov 4 postgresql rust actix-web

有这样一个模块代码(用于处理数据库):

use tokio_postgres::{NoTls, Error};

pub async fn hello() -> Result<(), Error> {

    // Connect to the database.
    let (client, connection) =
        tokio_postgres::connect("host=localhost user=postgres", NoTls).await?;

    // The connection object performs the actual communication with the database,
    // so spawn it off to run on its own.
    tokio::spawn(async move {
        if let Err(e) = connection.await {
            eprintln!("connection error: {}", e);
        }
    });

    // Now we can execute a simple statement that just returns its parameter.
    let rows = client
        .query("SELECT $1::TEXT", &[&"hello world"])
        .await?;

    // And then check that we got back the same string we sent over.
    let value: &str = rows[0].get(0);
    assert_eq!(value, "hello world");

    Ok(())
}
Run Code Online (Sandbox Code Playgroud)

问题:
这种情况下,对数据库的访问应该怎么写?
(该指南没有提及任何内容 - 或者我没有完全理解它。)
https://docs.rs/tokio-postgres/0.5.5/tokio_postgres/
在这种情况下,哪些机制将保护对数据库的访问来自sql注入?
需要最简单的通用用例。

Neo*_*ium 7

client.query(statement, params)会将第一个参数转换statement为准备好的语句并使用params.

为了避免 SQL 注入,请确保所有用户数据都在第二个params参数中传递。

不要这样做:

let id = "SOME DATA FROM THE USER";

let rows = client
  .query(format!("SELECT * FROM SomeTable WHERE id = {}", id), &[])
  .await?;
Run Code Online (Sandbox Code Playgroud)

做这个:

let id = "SOME DATA FROM THE USER";

let rows = client
  .query("SELECT * FROM SomeTable WHERE id = $1", &[&id])
  .await?;
Run Code Online (Sandbox Code Playgroud)

解释:

tokio-postgres大多数客户端方法中 (query*execute*) 可以接受sql 语句的&str或。Statement如果传递 a ,&str它将Statement为您创建一个准备好的语句(对象)。