tokio-postgres 和数据库查询
问题:tokio-postgres 和数据库查询 有这样一个模块代码(用于处理数据库): use tokio_postgres::{NoTls, Error}; pub async fn hello() -> Result<(), Error> { // Connect to the database. let (client, connection) = tokio_postgres::conn
·
问题:tokio-postgres 和数据库查询
有这样一个模块代码(用于处理数据库):
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(())
}
问题:
在这种情况下,应该如何编写对数据库的访问?
(指南没有说任何关于它的内容 - 或者我没有完全理解它。)
https://docs.rs/tokio-postgres/0.5.5/tokio_postgres/
在这种情况下,什么机制可以保护对数据库的访问免受 sql 注入?
需要最简单的通用用例。
解答
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?;
做这个:
let id = "SOME DATA FROM THE USER";
let rows = client
.query("SELECT * FROM SomeTable WHERE id = $1", &[&id])
.await?;
解释:
在tokio-postgres
中,大多数客户端方法(query*
或execute*
)可以接受&str
或Statement
用于 sql 语句。如果传递一个&str
它将为您创建一个准备好的语句(Statement
对象)。
更多推荐
已为社区贡献19918条内容
所有评论(0)