java程序调用Oracle存储过程

一:编写加载oracle驱动,连接和关闭资源的工具类

import java.sql.*;

public class SQLHelper1 {

    static {
        try{
            Class.forName("oracle.jdbc.driver.OracleDriver");
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    //只能在当前类中调用
    private SQLHelper1(){}
  
    public static Connection getConnection(){
        //Connection conn = null;
        String url = "jdbc:oracle:thin:@127.0.0.1:1521:orcl";
        String dbname="scott";
        String dbpwd="m123";
        try{
            return DriverManager.getConnection(url,dbname,dbpwd);
          
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
  
    }
    public static void close(Connection conn,PreparedStatement stmt,ResultSet rs){
        try{
            if(rs!=null){
                rs.close();
            }
          
        }catch(Exception e){
            e.printStackTrace();
          
        }
        try{
            if(stmt!=null){
                stmt.close();
            }
          
        }catch(Exception e){
            e.printStackTrace();
          
        }
        try{
            if(conn!=null){
                conn.close();
            }
          
        }catch(Exception e){
            e.printStackTrace();
          
        }
      
    }
}
二:直接调用存储过程:

//演示java程序去调用oracle的存储过程案例
import java.sql.*;

public class TestOraclePro {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Connection conn  = null;
        CallableStatement stmt = null;
        //调用oracle存储过程
        String sql = "{call sp_pro4(?,?)}";
        try{
            conn = SQLHelper1.getConnection();
            stmt = conn.prepareCall(sql);
            stmt.setString(1, "SMITH");
            stmt.setInt(2, 10);
            int rs = stmt.executeUpdate();
            if(rs!=0){
                System.out.println("操作成功!");
              
            }
          
        }catch(Exception e){
            e.printStackTrace();
        }finally{
            SQLHelper1.close(null, stmt, conn);
        }
      
    }

}

你可能感兴趣的:(java,oracle,sql,jdbc)