如何解决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
执行。
为安全起见,请确保在第二个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*
)都可以为sql语句接受&str
或Statement
。如果传递了&str
,它将为您创建一个准备好的语句(Statement
对象)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。