为什么要使用 Statement,如果 PreparedStatement 提高了性能

Why to use Statement, if PreparedStatement improves performance

根据 PreparedStatement in the JDBC docs, I see that it improves the performance compared to Statement 的解释。

那么为什么我们仍然使用 Statement 并且它没有被弃用呢?能解释一下吗。

如文档中所述,PreparedStatement 在多次执行查询时通常优于正常的 Statement

An object that represents a precompiled SQL statement.

A SQL statement is precompiled and stored in a PreparedStatement object. This object can then be used to efficiently execute this statement multiple times.

这就是 PreparedStatement 的用途。但并非一切都与性能有关:当查询中没有变量且所有内容都被硬编码并且要执行一次时,Statement 使用起来 更简单 。如果您只打算 运行 一次硬编码查询,那么创建一个具有所有潜在好处的准备好的语句就没有多大意义。事实上,在这种情况下,如果您使用 PreparedStatement 它不会有太大差异,因为执行的方法是相同的,例如Statement#executeQuery() 因为 PrepareStatementStatement.

的子类

PreparedStatement 在数据库服务器端分配了一些资源,而简单的 Statement 则没有。执行单个 SQL

时可能会导致一些性能差异