本文介绍了哪个更快?声明或PreparedStatement的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在网络中可以找到这样的代码:

Often, in the network can be found code like this:

private static final String SQL = "SELECT * FROM table_name";
....

并且对于此SQL查询使用PreparedStatement。为什么?

据我所知,PreparedStatement花时间预编译SQL语句。事实证明,Statement比PreparedStatement更快。或者我错了?

and for this SQL query is used PreparedStatement. Why?
As i know, PreparedStatement spend time to precompile SQL statement. It turns out so that the Statement is faster than a PreparedStatement. Or I'm mistaken?

推荐答案

当您必须多次运行相同的语句,使用不同的数据时,准备好的语句要快得多。那是因为SQL只会验证一次查询,而如果你只是使用一个语句,它每次都会验证查询。

Prepared statements are much faster when you have to run the same statement multiple times, with different data. Thats because SQL will validate the query only once, whereas if you just use a statement it will validate the query each time.

使用PreparedStatements的另一个好处是避免造成SQL注入漏洞 - 尽管在您的情况下您的查询非常简单,但您没有遇到过。

The other benefit of using PreparedStatements is to avoid causing a SQL injection vulnerability - though in your case your query is so simple you haven't encountered that.

对于您的查询,运行预准备语句与语句之间的区别可能是微不足道。

For your query, the difference between running a prepared statement vs a statement is probably negligible.

编辑:在回复下面的评论时,您需要仔细查看DAO类,看看它在做什么。例如,每次调用该方法时,它都会重新创建预准备语句,那么您将失去使用预准备语句的任何好处。

In response to your comment below, you will need to look closely at the DAO class to see what it is doing. If for example, each time the method is called it re-creates the prepared statement then you will lose any benefit of using prepared statements.

你想要实现的是你的持久层的封装,以便它们不是特定的调用MySQL或Postgres或者你正在使用的任何东西,同时利用准备好的语句之类的性能和安全性优势。要做到这一点,你需要依赖Java自己的对象,比如PreparedStatement ,.

What you want to achieve, is the encapsulation of your persistence layer so that their is no specific call to MySQL or Postgres or whatever you are using, and at the same time take advantage of the performance and security benefits of things like prepared statements. To do this you need to rely on Java's own objects such as PreparedStatement,.

我个人会建立自己的DAO类进行CRUD操作,使用下面的Hibernate和Java持久性API将所有内容封装起来,并且应该使用预准备语句来获得安全性好处。如果你有一个特定的用例来进行重复操作,那么我倾向于将它包装在它自己的对象中。

I personally would build my own DAO class for doing CRUD operations, using Hibernate underneath and the Java Persistence API to encapsulate it all, and that should use prepared statements for the security benefits. If you have a specific use-case for doing repeated operations, then I would be inclined to wrap that within its own object.

Hibernate可以配置为使用任何数据库供应商您正在使用XML文件,因此它提供了持久层的非常巧妙的封装。但是,要想做到这一点,这是一个非常复杂的产品!

Hibernate can be configured to use whatever database vendor you are using via an XML file, and thus it provides really neat encapsulation of your persistence layer. However, it is quite a complicated product to get right!

这篇关于哪个更快?声明或PreparedStatement的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 01:48