为了提高性能,我是否应该总是更喜欢使用准备好的 SQL 语句?
我的理解是,准备好的语句在服务器上编译一次,从而节省了重复解析、优化等的开销。显然,我应该总是更喜欢对运行多次的查询使用准备好的语句。
这种方法有什么缺点吗?
我正在使用 ODBC (libodbc++) 从 C++ 到 MySQL。
My understanding is that a prepared statement is compiled on the server once, thus saving the overhead of repeating parsing, optimization etc. Apparently, I should always prefer using prepared statements for queries that run more than once.
Are there any cons to this approach?
I am using ODBC (libodbc++) from C++ to MySQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
准备好的语句:
Prepared Statements:
大量活动准备好的语句会消耗额外的服务器内存。例如,对于嵌入式平台(例如 iPhone 上的 sqlite 数据库)来说,这可能是一个问题。
Larger numbers of active prepared statements consume additional server memory. For example, it can be an issue for embedded platforms (e.g. sqlite database on IPhone).
为了安全的好处,您应该总是更喜欢使用准备好的语句。它们几乎消除了 SQL 注入的漏洞,而您不必担心 SQL 转义值。
但是,如果您的查询不经常运行(每个请求少于一次),则准备好的语句可能需要更长的时间才能运行。使用准备好的语句需要两次调用:一次准备它,一次执行它。通过一条临时语句,这两个步骤一举完成,无需等待服务器说“好的,编译完成”。
所有这一切的结果是,如果您担心性能,并且您的查询只运行一次,则临时查询可能会更快一些。但安全方面的好处几乎总是超过准备声明所需的额外时间。
You should always prefer working with prepared statements for the security benefits. They all but eliminate vulnerability to SQL injection, without you having to worry about SQL-escaping values.
If you have a query that doesn't run often, though (less than once per request), a prepared statement can take longer to run. It takes two calls to use a prepared statement: once to prepare it, and once to execute it. With an ad-hoc statement, those two steps are done in one fell swoop, and there's no waiting for the server to say "ok, done compiling".
The upshot of all that being, if you're worried about performance, and your query only runs once, an ad-hoc query might be a little faster. But the security benefits almost always outweigh the extra little bit of time it takes to prepare a statement.