1. 程式人生 > >JDBC調用MySQL的調用過程CallableStatement

JDBC調用MySQL的調用過程CallableStatement

args port ger rep 是否 nag ace exception mysql

調用過程可以當作函數理解,具體參考本人博文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(); } } } } }

JDBC調用MySQL的調用過程CallableStatement