JDBC调用MySQL的调用过程CallableStatement

调用过程可以当作函数理解,具体参考本人博文https://www.cnblogs.com/xixixing/p/9720261.html

MySQL的test数据库中已经创建好存储过程p2(n),实现筛选school表id>n的信息

CallableStatement callStatement=con.prepareCall("{call p2(?)}");  调用test数据库的调用过程p2
callStatement.setString(1,"2");    赋值,筛选school表id>2的信息
ResultSet rs=callStatement.executeQuery();  结果展示

import java.sql.*;

public class Demo {
    public static void main(String[] args) {
        //定义为null,因为它们是数据流,之后要finally依次关闭
        Connection con = null;//连接
        CallableStatement call=null;//调用过程语句接口
        ResultSet rs = null;//结果集接口
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");//加载驱动
            String url = "jdbc:mysql://localhost:3306/test?serverTimezone=UTC&characterEncoding=utf8&useSSL=false";
            con = DriverManager.getConnection(url, "root", "123456");//连接数据库test
            //System.out.println(con);//查看结果,确认是否连接成功
            call=con.prepareCall("{call p2(?)}");
            call.setString(1,"2");//给通配符?赋值,即n=2
            rs=call.executeQuery();
            System.out.println("id\tname\tsex\tbirthday");
            while (rs.next()) {//下一行
                int id = rs.getInt("id");//或1,第一列值
                String name = rs.getString(2);
                String sex = rs.getString(3);
                String birthday = rs.getString(4);
                System.out.println(id + "\t" + name + "\t" + sex + "\t" +birthday);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {//注意流的关闭顺序
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (call != null) {
                try {
                    call.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/xixixing/p/9720427.html