zoukankan      html  css  js  c++  java
  • 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	name	sex	birthday");
                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 + "	" + name + "	" + sex + "	" +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();
                    }
                }
            }
        }
    }
  • 相关阅读:
    黑客防线
    基于onvif的码流转换专利
    8168开发之---1g内存换成512M的内存映射配置
    图像处理之基础---内积、点积
    3s 简介
    嵌入式开发之工具---比开发手册更重要的一个命令 man page
    图像处理之基础---频域分析
    lbp纹理特征
    28.Docker介绍与目录
    09.客户端集成IdentityServer
  • 原文地址:https://www.cnblogs.com/xixixing/p/9720427.html
Copyright © 2011-2022 走看看