码迷,mamicode.com
首页 > 数据库 > 详细

使用JDBC操作存储过程

时间:2014-08-24 18:08:12      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:存储过程   jdbc   callablestatement   

 

使用JDBC操作存储过程,可以借助于一个借口CallableStatement实现。

此时调用存储过程的sql语句为:{call procedure_name [(arg1),(arg2)]}

而CallableStatement可以通过数据库连接对象的prepareCall()方法获得

例如:

conn.prepareCall(sql);

如果此时的存储过程有输出参数,可以通过他的registerOutParameter()方法将输出参数注册为JDBC类型。例如:

registerOutParameter(int parameterIndex,int sqlType)

下面看一个统计学生人数示例,首先看数据库中的记录:

bubuko.com,布布扣

不难看出学生表中公有七条记录。

下面写一个存储过程统计学生表中的人数。

create or replace procedure getStudentCount(v_student out number) is
begin
  select count(*) into v_student from student;
end getStudentCount;

然后测试一下这个存储过程:

declare
  v_count number;
begin
  getstudentCount(v_count);
  dbms_output.put_line(v_count);
end;

输出结果为7。存储过程没有问题。

然后在看如何使用JDBC调用存储过程。

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;


public class ProcedureDemo {
	public static void main(String[] args) {
		Connection conn = null;
		int studentCount = 0;
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", 
					"myhr", "myhr");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		String sql = "{call getStudentCount(?)}";
		try {
			CallableStatement proc = conn.prepareCall(sql);
			proc.registerOutParameter(1, java.sql.Types.INTEGER);
			proc.execute();
			studentCount = proc.getInt(1);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		System.out.println(studentCount);
	}
}

这时在控制台输出7,证明调用存储过程成功。
 

 

使用JDBC操作存储过程

标签:存储过程   jdbc   callablestatement   

原文地址:http://blog.csdn.net/u011740475/article/details/38796601

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!