`

java 里 存储过程的使用

阅读更多
package poceduretest;

import java.sql.*;

class MainTest
{
  public static void main(String[] args)
  {
    java.sql.Connection con = ConnectionManager.getConnection();  //先获得连接
    /**
     * 基本存储过程调用
     */
    try
    {
      java.sql.CallableStatement cs = con.prepareCall("{call sp_num}");  //传入的参数是call 和 存储过程名
      cs.execute();
      if(cs.execute())
      {
      
      }else
      {
         java.sql.ResultSet r = cs.getResultSet();
      // 输出记录集里的数据
          while (r.next())
          {
             System.out.print(r.getString(1));
             System.out.print("\t" + r.getString(2));
             System.out.print("\t" + r.getInt(3));
             System.out.println("\t" + r.getInt(4));
          }
      }
    }
    catch (SQLException ex)
    {
    }



    /**
     * 调用有参数的存储过程1
     */
    try
    {
      int x = 15;
      java.sql.CallableStatement cs = con.prepareCall("{call sp_num1(?)}"); //此内的?与存储过程里的输出和输入参数一致
      cs.setInt(1, x);

      // 执行存储过程
      cs.execute();

      java.sql.ResultSet r = cs.getResultSet();
      // 输出记录集里的数据
      while (r.next())
      {
        System.out.print(r.getString(1));
        System.out.println("\t" + r.getString(2));
      }
    }
    catch (SQLException ex)
    {
    }

    /**
     * 调用有参数的存储过程2
     */




    try
    {
      String name = "business";
      java.sql.CallableStatement cs = con.prepareCall("{call sp_num2(?)}");
      cs.setString(1, name);

      // 执行存储过程
      cs.execute();

      java.sql.ResultSet r = cs.getResultSet();
      // 输出记录集里的数据
      while (r.next())
      {
        System.out.print(r.getString(1));
        System.out.println("\t" + r.getString(2));
      }
    }
    catch (SQLException ex)
    {
    }



    /**
     * 带有输出参数的存储过程
     */
    try
    {
      String name = "business";
      java.sql.CallableStatement cs = con.prepareCall("{call sp_num5(?,?)}");

      cs.registerOutParameter(1, java.sql.Types.INTEGER);
      cs.setInt(2, 5);


      cs.execute();


      System.out.println(cs.getInt(1));
    }
    catch (SQLException ex)
    {
    }

    /**
     * 返回多个结果集的存储过程
     */




    try
    {
      java.sql.CallableStatement cs = con.prepareCall("{call sp_num6}");
      cs.execute();

      do
      {
        java.sql.ResultSet t = cs.getResultSet();
        while (t.next())
        {
          System.out.print(t.getString(1));
          System.out.println("\t" +t.getString(2));
        }

      }while(cs.getMoreResults());
    }
    catch (SQLException ex)
    {
    }
  }
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics