03. JDBC 预编译SQL语句 & 储存过程调用

来源:互联网 发布:重庆计划软件 编辑:程序博客网 时间:2024/05/16 04:44

在JDBC中,Statement接口用于进行Java程序和数据库之间的数据传输,具体类有3个实现,如下:
Statement用于对数据库进行通用访问,在运行时使用静态SQL语句时使用。 PreparedStatement当计划要多次使用SQL语句时使用。PreparedStatement接口在运行时接受输入参数。CallableStatement当想要访问数据库存储过程时使用。CallableStatement接口也可以接受运行时输入参数。


JDBC 预编译SQL语句

PreparedStatement 用于预编译模板SQL语句,这对于多次执行使用同一个模板的SQL语句,在性能和代码灵活性上有显著地提高;
PreparedStatement 对象使用 ? 作为占位符,即参数标记;
PreparedStatement 使用 setXXX( index,value) 方法将值绑定到参数中,每个参数标记是其顺序位置引用,注意 index 从 1 开始;
PreparedStatement  对象执行SQL语句,同样可以使用 execute(),executeQuery(),executeUpdate() 方法;
示例:
1
Class.forName("com.mysql.jdbc.Driver");
2
Connection connection = DriverManager.getConnection("jdbc:mysql//localhost/bookRama","root","123");
3
4
PreparedStatement pstmt = conncection.prepareStatement("select id form books where author=? and price>?");
5
pstmt.setString(1,"assad");
6
pstmt.setFloat(2,10.0);
7
ResultSet resultset = pstmt.execute();
8
.....//处理结果集
9
pstmt.setString(1,"Alex");
10
pstmt.setFloat(2,8.0);
11
resultset = pstmt.execute();
12
.....//处理结果集
13
pstmt.close();

JDBC 储存过程调用

CallableStatement 对象用于调用数据库中的储存过程;
CallableStatement 同样使用模板SQL语句的组织形式,对于过程的 IN 参数,只要使用 setXXX() 绑定参数就好;对于 OUT,INOUT 参数,就需要使用一个 registerOutParameter() 方法注册返回参数;

以下示例:
假设数据库中有储存过程 function matchName(firstname varchar2,lastname verchar2);
返回某个表中与 firstname、lastname 都参数匹配的名字记录个数;
1
Class.forName("com.mysql.jdbc.Driver");
2
Connection connection = DriverManager.getConnection("jdbc:mysql//localhost/demo","root","123");
3
4
CallableStatement statment = connection.prepareCall("{ ? = call matchName(?,?) }");
5
statement.setString(2,"White");   //绑定IN参数
6
statement.setString(3,"Lambda");
7
statement.registerOutParameter(1,Types.INTEGER);   //注册OUT参数类型
8
statement.execute();
9
10
int result = statement.getInt(1);