准备好的语句的最佳实践;什么时候该做,什么时候不该做
我最近开始在 Web 应用程序中再次使用准备好的语句,并且我知道不鼓励对所有事务使用准备好的语句。我不知道什么时候最好使用准备好的语句。
我读过何时使用和不使用它们,但没有一个示例真正讲述了使用它们的最佳实践。
我试图弄清楚哪些数据库调用我应该使用它们,哪些数据库调用我不应该使用它们。
例如,MySQL 网站在下一页的“何时使用准备好的语句”中提到了它 准备语句-MySQL
I recently have began using prepared statements again in a web application, and I know that it is discouraged to use prepared statements for all the transactions. What I do not know is when it is best to use prepared statements or not.
I have read of when to use and not use them, but none of the examples really tell best practice of using them.
I am trying to figure out which database calls I should be using them for and which ones I should not.
For Example the MySQL website mentions it in "When to use prepared statements" on the following page Prepared Statements-MySQL
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
决定是否使用PreparedStatement 的一般经验法则是:
根据您引用的文章,我认为准备语句不如普通查询或存储过程有用的原因列表如下:
The general thumb rule in deciding whether to go for a PreparedStatement or not is:
Going by the article that you have referenced, the list of reasons where I believe Prepared Statements are less useful than normal queries or stored procedures are:
为了防止 SQL 注入,最好在 Java 中使用准备好的语句
。有关更多信息:SQL 注入准备好的声明?
In order to prevent SQL Injection it is better to use prepared statements in Java
For more information: SQL injections with prepared statements?
ReadyStatements 有两个主要用途:
这两个原因都是非常令人信服的理由,几乎总是可以证明使用PreparedStatement是合理的,但是根据您使用数据库的方式,您可能会遇到PreparedStatement不允许您执行您想要的操作的情况。
作为这种情况的一个例子,我曾经编写过一个工具,它根据某些抽象的运行时属性动态生成表名,这意味着我必须能够使用可变表名进行 SQL 查询;你无法使用PreparedStatement 获得这些内容,因此我不得不使用原始语句和一些预处理技巧来重新利用PreparedStatement 进行SQL 注入保护。
PreparedStatements have two major uses:
Both of these reasons are a very compelling ones to justify using PreparedStatement almost always, however depending on how you're using the database you may hit a point where PreparedStatement won't allow you to do what you want.
As an example of such case, I've once written a tool which generated table names on the fly based on runtime properties of certain abstractions which meant that I had to be able to have SQL queries with mutable table names; you can't get those with PreparedStatement so I had to use raw Statements and some preprocessing trickery to get back to utilizing PreparedStatements for SQL injection protection.