首页 > 代码库 > 调用存储过程

调用存储过程

/**************调用存储过程****************/
 public static void main(String[] args) {
  try {
   Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  Connection conn = null;
  CallableStatement callStm = null;
  try {
   conn = DriverManager.getConnection(
     "jdbc:sqlserver://localhost:1434;databaseName=StuDB", "sa",
     "sasa");
   //创建执行存储过程命令对象
   callStm = conn.prepareCall("{call proc_getStudentNameByNum(?,?)}");//(?,?)表示存储过程的参数
   callStm.setInt("stuNum", 123906);//给输入参数赋值
   callStm.registerOutParameter("stuName", java.sql.Types.NVARCHAR);//设置输出参数
   callStm.executeUpdate();//执行存储过程
   String result = callStm.getString("stuName");//获取输出参数的值
   System.out.println(result);
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }finally{
   try {
    callStm.close();
    conn.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  }
 }