为什么使用mysql预处理语句比使用普通转义功能更安全? [英] Why is using a mysql prepared statement more secure than using the common escape functions?

查看:95
本文介绍了为什么使用mysql预处理语句比使用普通转义功能更安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另一个问题中有一个评论,内容如下:

There's a comment in another question that says the following:

"关于数据库查询, 总是尝试并使用准备好的 参数化查询. mysqli和 PDO库支持此功能.这是 比转义绝对安全 诸如 mysql_real_escape_string."

"When it comes to database queries, always try and use prepared parameterised queries. The mysqli and PDO libraries support this. This is infinitely safer than using escaping functions such as mysql_real_escape_string."

所以,我想问的是:为什么准备好的参数化查询更安全?

So, what i want to ask is: Why are prepared parameterized queries more secure?

推荐答案

我认为这里的人们所缺少的重要一点是,使用支持参数化查询的数据库,无需担心转义".数据库引擎不会将绑定的变量组合到SQL语句中,然后再解析整个事物.绑定变量保持独立,并且永远不会解析为通用SQL语句.

An important point that I think people here are missing is that with a database that supports parameterized queries, there is no 'escaping' to worry about. The database engine doesn't combine the bound variables into the SQL statement and then parse the whole thing; The bound variables are kept separate and never parsed as a generic SQL statement.

这就是安全性和速度的来源.数据库引擎知道占位符仅包含数据,因此永远不会将其解析为完整的SQL语句.当您一次准备一条语句然后执行多次时,就会提速.典型示例是将多个记录插入到同一表中.在这种情况下,数据库引擎只需解析,优化等一次.

That's where the security and speed comes from. The database engine knows the placeholder contains data only, so it is never parsed as a full SQL statement. The speedup comes when you prepare a statement once and then execute it many times; the canonical example being inserting multiple records into the same table. In this case, the database engine needs to parse, optimize, etc. only once.

现在,数据库抽象库是一个难题.他们有时通过仅将绑定变量以适当的转义插入SQL语句中来伪造它.不过,这比自己动手做要好.

Now, one gotcha is with database abstraction libraries. They sometimes fake it by just inserting the bound variables into the SQL statement with the proper escaping. Still, that is better than doing it yourself.

这篇关于为什么使用mysql预处理语句比使用普通转义功能更安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆