Statement、Preparestatement和CallableStatement

来源:互联网 发布:onavo protect mac版 编辑:程序博客网 时间:2024/06/05 14:59

一、Statement、Preparestatement和CallableStatement都是接口。
在 Java™ Platform Standard Ed. 8 帮助文档中,

对Statement有如下解释:

Interface StatementAll Superinterfaces: AutoCloseable, Wrapper All Known Subinterfaces: CallableStatement, PreparedStatement

对Preparestatement有如下解释:

Interface PreparedStatementAll Superinterfaces: AutoCloseable, Statement, Wrapper All Known Subinterfaces: CallableStatement

对CallableStatement有如下解释

Interface CallableStatementAll Superinterfaces: AutoCloseable, PreparedStatement, Statement, Wrapper

可见,

CallableStatement继承自PreparedStatementPreparedStatement继承自StatementStatement继承自AutoCloseable, Wrapper

二、Statement、Preparestatement和CallableStatement的不同
Statement
The object used for executing a static SQL statement and returning the results it produces.

Statement 用来执行一条【静态】SQL语句,并且返回结果。但是,每条Statement语句只能返回【指定条件】的查找结果集。

Preparestatement
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.

Preparestatement是预编译的,变成了【动态】执行。在继承了Statement之后,添加了处理IN参数的方法。通过接收的不同的参数,执行不同的指令,返回不同条件的结果集。

CallableStatement
The interface used to execute SQL stored procedures.
If used, the result parameter must be registered as an OUT parameter.

 CallableStatement也是预编译的。 它通常是用来调用存储过程,一旦使用了它,结果部分必须注册为OUT参数。 其在继承了Preparestatement之后,添加了处理OUT参数的方法。 通过接收的不同的参数,执行不同的指令,返回不同条件的结果集。

三、Statement、Preparestatement和CallableStatement的不同和使用场景:

Statement

Statement每次执行sql语句,数据库都要执行sql语句的编译,最好用于仅执行一次查询并返回结果的情形,效率高于PreparedStatement

Preparestatement

1. 在执行可变参数的SQL时,PreparedStatement比Statement的效率高。3. 对于多次重复执行的语句,使用PreparedStament效率会更高一点。

CallableStatement

在调用存储过程的时候使用,因为存储过程往往有输出参数。