java 调用存储过程案列分析

3/8/2017来源:ASP.NET技巧人气:1494

1:创建存储过程

此存储过程通过传入的参数(Name),返回一个参数(address)。

create or replace PRocedure demo_procedure(namedemo in varchar2,addressdemo out varchar2) as begin  select address into addressdemo from system.demo where name=namedemo; end;

2:java部分:调用存储过程时,要用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.Statement;  
import java.sql.Types;  
  
public class TestProcedureTwo {  
  public TestProcedureTwo() {  
  }  
  public static void main(String[] args ){  
    String driver = "Oracle.jdbc.driver.OracleDriver";  
    String strUrl = "jdbc:oracle:thin:@localhost:1521:myoracle";  
    Statement stmt = null;  
    ResultSet rs = null;  
    Connection conn = null;  
    try {  
      Class.forName(driver);  
      conn =  DriverManager.getConnection(strUrl, "system", "admin");  
      CallableStatement proc = null; 
      proc = conn.prepareCall("{ call dem_procedure(?,?) }");  //调用存储过程
      proc.setString(1, "kalision");   //存储过程传入的参数
      proc.registerOutParameter(2, Types.VARCHAR);  //存储过程输出的参数
      proc.execute();  
      String testPrint = proc.getString(2);  
      System.out.println("存储过程返回的值是:"+testPrint);  
    }  
    catch (SQLException ex2) {  
      ex2.printStackTrace();  
    }  
    catch (Exception ex2) {  
      ex2.printStackTrace();  
    }  
    finally{  
      try {  
        if(rs != null){  
          rs.close();  
          if(stmt!=null){  
            stmt.close();  
          }  
          if(conn!=null){  
            conn.close();  
          }  
        }  
      }  
      catch (SQLException ex1) {  
      }  
    }  
  }  
}