jdbcjdbctm
4 - statement
本概述是从《jdbctm database access from javatm: a tutorial and annotated reference 》这本书中摘引来的。javasoft 目前正在准备这本书。这是一本教程,同时也是 jdbc 的重要参考手册,它将作为 java 系列的组成部份在 1997 年春季由 addison-wesley 出版公司出版。
4.1 概述
statement 对象用于将 sql 语句发送到数据库中。实际上有三种 statement 对象,它们都作为在给定连接上执行 sql 语句的包容器:statement、preparedstatement(它从 statement 继承而来)和 callablestatement(它从 preparedstatement 继承而来)。它们都专用于发送特定类型的 sql 语句: statement 对象用于执行不带参数的简单 sql 语句;preparedstatement 对象用于执行带或不带 in 参数的预编译 sql 语句;callablestatement 对象用于执行对数据库已存储过程的调用。
statement 接口提供了执行语句和获取结果的基本方法。preparedstatement 接口添加了处理 in 参数的方法;而 callablestatement 添加了处理 out 参数的方法。
4.1.1 创建 statement 对象
建立了到特定数据库的连接之后,就可用该连接发送 sql 语句。statement 对象用 connection 的方法 createstatement 创建,如下列代码段中所示:
connection con = drivermanager.getconnection(url, sunny, );
statement stmt = con.createstatement();
为了执行 statement 对象,被发送到数据库的 sql 语句将被作为参数提供给 statement 的方法:
resultset rs = stmt.executequery(select a, b, c from table2);
4.1.2 使用 statement 对象执行语句
statement 接口提供了三种执行 sql 语句的方法:executequery、executeupdate 和 execute。使用哪一个方法由 sql 语句所产生的内容决定。
方法 executequery 用于产生单个结果集的语句,例如 select 语句。
方法 executeupdate 用于执行 insert、update 或 delete 语句以及 sql ddl(数据定义语言)语句,例如 create table 和 drop table。insert、update 或 delete 语句的效果是修改表中零行或多行中的一列或多列。executeupdate 的返回值是一个整数,指示受影响的行数(即更新计数)。对于 create table 或 drop table 等不操作行的语句,executeupdate 的返回值总为零。
方法 execute 用于执行返回多个结果集、多个更新计数或二者组合的语句。因为多数程序员不会需要该高级功能,所以本概述后面将在单独一节中对其进行介绍。
执行语句的所有方法都将关闭所调用的 statement 对象的当前打开结果集(如果存在)。这意味着在重新执行 statement 对象之前,需要完成对当前 resultset 对象的处理。
应注意,继承了 statement 接口中所有方法的 preparedstatement 接口都有自己的 executequery、executeupdate 和 execute 方法。statement 对象本身不包含 sql 语句,因而必须给 statement.execute 方法提供 sql 语句作为参数。preparedstatement 对象并不将 sql 语句作为参数提供给这些方法,因为它们已经包含预编译 sql 语句。callablestatement 对象继承这些方法的 preparedstatement 形式。对于这些方法的 preparedstatement 或 callablestatement 版本,使用查询参数将抛出 sqlexception。
