我们什么时候应该使用 PreparedStatement 而不是 Statement ? [英] When should we use a PreparedStatement instead of a Statement?
问题描述
我知道使用PreparedStatement
的好处,就是
I know the advantages of using PreparedStatement
, which are
- 查询由数据库服务器重写和编译
- 防止 SQL 注入
但是我想知道我们什么时候用它代替Statement
?
But I want to know when we use it instead of Statement
?
推荐答案
查询由数据库服务器重写和编译
Query is rewritten and compiled by the database server
如果你不使用准备好的语句,数据库服务器将必须解析,并计算一个语句的执行计划每次运行它.如果你发现你将运行相同的语句多次(不同参数)那么值得准备声明一次并重用它准备好的声明.如果你是查询数据库即席然后可能没有什么好处这个.
If you don't use a prepared statement, the database server will have to parse, and compute an execution plan for the statement each time you run it. If you find that you'll run the same statement multiple times (with different parameters) then its worth preparing the statement once and reusing that prepared statement. If you are querying the database adhoc then there is probably little benefit to this.
防止 SQL 注入
Protected against SQL injection
这几乎是你的优势总是想要一个很好的理由每次都使用 PreparedStatement
.这是不得不这样做的结果参数化查询,但它确实让它运行起来更安全.这只有一次我能想到这个如果你是,那就没用了允许临时数据库查询;你可能只是使用声明对象,如果你正在制作原型应用程序,它对你来说更快,或者如果查询不包含参数.
This is an advantage you almost
always want hence a good reason to
use a PreparedStatement
everytime.
Its a consequence of having to
parameterize the query but it does
make running it a lot safer. The
only time I can think of that this
would not be useful is if you were
allowing adhoc database queries; You
might simply use the Statement
object if you were prototyping the
application and its quicker for you,
or if the query contains no
parameters.
这篇关于我们什么时候应该使用 PreparedStatement 而不是 Statement ?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!