SQL 参数内部如何工作?
当我和一位同事浏览 SO 时,我们遇到了一个有关 SQL 注入的问题,这让我们想知道:参数化查询内部是如何工作的?您正在使用的 API(假设它支持参数化查询)是否执行串联,将查询与参数组合起来?或者参数是否与查询分开进入 SQL 引擎,并且根本不执行任何连接?
谷歌并没有提供多大帮助,但也许我们没有搜索到正确的东西。
A coworker and I were browsing SO when we came across a question about SQL Injection, and it got us wondering: how do parametrized queries work internally? Does the API you are using (assuming it supports parametrized queries) perform concatenation, combining the query with the parameters? Or do the parameters make it to the SQL engine separately from the query, and no concatenation is performed at all?
Google hasn't been very helpful, but maybe we haven't searched for the right thing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这些参数与查询分开传送到 SQL 引擎。为参数化查询计算或重用执行计划,然后由sql引擎带参数执行查询。
The parameters make it to the SQL engine separately from the query. Execution plan calculated or reused for the parametrized query, and then query is executed by sql engine with parameters.
参数使其完好无损地到达 SQL 服务器,并单独“打包”,元数据指示其类型,无论是输入还是输出等。正如 Alex Reitbort 指出的那样,之所以如此,是因为参数化语句是一个服务器级别的概念,而不仅仅是一个方便的概念。从各个连接层调用命令的方式。
Paramters make it to the SQL server intact, and individually "packaged" with meta data indicating their type, whether Input or Output etc. As Alex Reitbort points out, it is so because the parametrized statements are a server level concept, not merely a convenient way of invoking commands from various connection layers.
我怀疑 SQL SERVER 从给定的参数化查询构建一个完整的查询字符串,其中参数列表连接在其中。
它很可能解析给定的参数化命令字符串,根据保留字和符号(SELECT、FROM、 “,”,“+”等)。在该数据结构中,存在诸如表名、文字等值的属性/位置。正是在这里,它将(从列表中)传入的每个参数复制(逐字)到该结构的适当部分。
所以你的 @UserName 值: 'x';delete from users --
并不是永远不需要转义,只是用作它真正的文字值。
I doubt that SQL SERVER builds a complete query string from the given parametrized query where the parameter list is concatenated in.
It most likely parses the given parametrized command string splitting it into an internal data structure based on reserved words and symbols (SELECT, FROM, ",", "+", etc). Within that data structure, there are properties/places for values like table names, literals, etc. It is here that it copies (verbatim) the each passed in parameter (from the list) into the proper section of that structure.
so your @UserName value of: 'x';delete from users --
in not never needs to be escaped, just used as the literal value it really is.
参数随查询一起传递(不在查询内),并在根据底层数据库通信协议发送时由 API 自动转义。
例如,您可能认为
这不是任何数据库协议实际使用的确切编码,但您明白了。
Parameters are passed along with the query (not within the query), and are automatically escaped by the API as they are sent in accordance with the underlying database communications protocol.
For example, you might have
That's not the exact encoding any database protocol actually uses, but you get the idea.