Java JDBC里如何取得Oracle存储过程返回的动态结果集
1个回答
展开全部
创建存储过程
create or replace procedure proc3(stid in student.stuid%type, stname out student.sname%type, stphone out student.phonenumber%type, stuadd out student.saddress%type)
as countnumber number;
begin
select count(*) into countnumber from student where stuid=stid;
if countnumber=1 then
select phonenumber into stphone from student where stuid=stid;
select saddress into stuadd from student where stuid=stid;
select sname into stname from student where stuid=stid;
else
dbms_output.put_line('返回值过多');
endif;
end;调用存储过程时,要用CallabelStatement的prepareCall 方法。结构:{call 存储过程名(?,?,...)}
在设置参数的时候,输入参数用set,输出参数要registerOutParameter。取出输出参数的值可以直接用CallabelStatement的get方法
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
public class Dao {
String driver="oracle.jdbc.driver.OracleDriver";
String url="jdbc:oracle:thin:@127.0.0.1:1521:orcl";
Connection conn=null;
CallableStatement cs=null;//PreparedStatement,Statement
ResultSet rs;
public void getConn(){
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, "scott", "tiger");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void callProc(){
try {
cs = conn.prepareCall("{call proc3(?,?,?,?)}");
cs.setInt(1, 1);
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.VARCHAR);
cs.execute();
String name = cs.getString(2);
String phone = cs.getString(3);
String address = cs.getString(4);
System.out.println("Name:"+name+"\t Phone:"+phone+"\t Address:"+address);
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (cs!=null) cs.close();
if(conn!=null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Dao dao = new Dao();
dao.getConn();
dao.callProc();
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询