package com.zhao.practice726_3;
import java.sql.CallableStatement;
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException;/**
* DBCallableStatement类 * Administrator * */ public class DBCallableStatement { /** * 驱动字符串 */ private static final String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // 加载JDBC驱动 /** * 连接数据库的URL */ private static final String dbURL = "jdbc:sqlserver://localhost:1433; DatabaseName=zhao726"; // 连接服务器和数据库Northwind /** * 用户名字符串 */ private static final String USER= "sa"; /** * 密码字符串 */ private static final String PASSWORD = "3221682"; /** * 数据库连接 */ Connection conn = null; /** * CallableStatement */ CallableStatement stat = null; static { try { Class.forName(driverName); } catch (ClassNotFoundException e) { e.printStackTrace(); } } /** * 获取数据库连接 * */ private Connection getConnection(){ try { conn = DriverManager.getConnection(dbURL, USER, PASSWORD);return conn;
} catch (SQLException e) { e.printStackTrace(); } return null; } /** * 获得CallableStatement对象 * @param sql sql语句 * CallableStatement */ public CallableStatement getPreparedStatement(String sql){ try { stat = getConnection().prepareCall(sql); System.out.println(sql); return stat; } catch (SQLException e) { e.printStackTrace(); } return null; } /** * 关闭所有打开的数据库连接 */ public void close(){ try{ if(stat != null){ stat.close(); } if(conn != null){ conn.close(); } }catch(SQLException e){ e.printStackTrace(); } } }
package com.zhao.practice726_3;
import java.sql.CallableStatement;
import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Types; /** * 测试类 * Administrator * */ public class TestCallableStatement {/**
* @param args */ public static void main(String[] args) { String sql = "{call sp_sum(?,?,?)}"; DBCallableStatement db = new DBCallableStatement(); //获得CallableStatement对象 CallableStatement stat = db.getPreparedStatement(sql); try { //设置参数 stat.setInt(1, 4); stat.setInt(2, 5); //注册第三个参数为int类型 stat.registerOutParameter(3, Types.INTEGER); if(!stat.execute()){ System.out.println(stat.getInt(3)); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally{ db.close(); } }}