我们什么时候应该使用 PreparedStatement 而不是 Statement ?

编程入门 行业动态 更新时间:2024-10-28 09:21:58
本文介绍了我们什么时候应该使用 PreparedStatement 而不是 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 ?

    本文发布于:2023-05-23 14:41:38,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1326116.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:什么时候   而不是   PreparedStatement   Statement

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!