初学JDBC,调用存储过程

时间:2022-02-21 21:13:59

在JDBC简单封装的基础上实现

public class UserDao{

  public static void testGetUser(String userName) throws Exception{

    Connection conn=null;

    CallableStatement callableStatement=null;

    ResultSet resultSet=null;

    try{

      conn=JdbcUtils.getConnetcion();

      String sql="{call addUser(?,?,?,?)}";//调用数据库addUser存储过程,有四个参数,最后一个参数是输出新数据的ID

      callableStatement=conn.prepareCall(sql);

      callableStatement.setString(1,"test");

      callableStatement.setDate(2,new java.sql.Date(System.currentTimeMillis()));

      callableStatement.setFloat(3,100f);

      callableStatement.registerOutParameter(4,Types.INTEGER);

      callableStatement.excuteUpdate();

      int id=callableStatement.getInt(4);//获得存储过程的输出参数值

    }finally{

      JdbcUtils.freeResource(resultSet,preparedStatement,conn);

    }

  }

}