JDBC調用MySQL的調用過程CallableStatement

調用過程能夠看成函數理解,具體參考本人博文https://www.cnblogs.com/xixixing/p/9720261.htmlhtml

MySQL的test數據庫中已經建立好存儲過程p2(n),實現篩選school表id>n的信息java

CallableStatement callStatement=con.prepareCall("{call p2(?)}");  調用test數據庫的調用過程p2
callStatement.setString(1,"2");    賦值,篩選school表id>2的信息
ResultSet rs=callStatement.executeQuery();  結果展現mysql

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();
                }
            }
        }
    }
}
相關文章
相關標籤/搜索