CallableStatement 인터페이스를 사용하여 SQL 저장 프로시저를 호출할 수 있습니다. Callable 문은 입력 매개변수, 출력 매개변수 또는 둘 다를 가질 수 있습니다.
CallableStatement의 개체를 만들 수 있습니다. (인터페이스) prepareCall() 사용 연결 방법 상호 작용. 이 메서드는 저장 프로시저를 호출하는 쿼리를 나타내는 문자열 변수를 허용하고 CallableStatement를 반환합니다. 개체.
프로시저 이름이 myProcedure라고 가정합니다. 데이터베이스에서 다음과 같이 호출 가능한 문을 준비할 수 있습니다.
//Preparing a CallableStatement
CallableStatement cstmt = con.prepareCall("{call myProcedure(?, ?, ?)}"); 그런 다음 CallableStatement 인터페이스의 setter 메서드를 사용하여 자리 표시자에 값을 설정하고 아래와 같이 execute() 메서드를 사용하여 호출 가능한 문을 실행할 수 있습니다.
cstmt.setString(1, "Raghav"); cstmt.setInt(2, 3000); cstmt.setString(3, "Hyderabad"); cstmt.execute();
프로시저에 대한 입력 값이 없는 경우 호출 가능한 문을 준비하고 아래와 같이 실행하면 됩니다.
CallableStatement cstmt = con.prepareCall("{call myProcedure()}");
cstmt.execute(); 예시
Dispatches라는 테이블이 있다고 가정합니다. 다음 데이터가 있는 MySQL 데이터베이스:
+--------------+------------------+------------------+----------------+ | Product_Name | Date_Of_Dispatch | Time_Of_Dispatch | Location | +--------------+------------------+------------------+----------------+ | KeyBoard | 1970-01-19 | 08:51:36 | Hyderabad | | Earphones | 1970-01-19 | 05:54:28 | Vishakhapatnam | | Mouse | 1970-01-19 | 04:26:38 | Vijayawada | +--------------+------------------+------------------+----------------+
그리고 아래와 같이 이 테이블에서 값을 검색하기 위해 myProcedure라는 프로시저를 만든 경우:
Create procedure myProcedure () -> BEGIN -> SELECT * FROM Dispatches; -> END //
예시
다음은 JDBC 프로그램을 사용하여 위에서 언급한 저장 프로시저를 호출하는 JDBC 예제입니다.
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CallingProcedure {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Getting the connection
String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//Preparing a CallableStateement
CallableStatement cstmt = con.prepareCall("{call myProcedure()}");
//Retrieving the result
ResultSet rs = cstmt.executeQuery();
while(rs.next()) {
System.out.println("Product Name: "+rs.getString("Product_Name"));
System.out.println("Date of Dispatch: "+rs.getDate("Date_Of_Dispatch"));
System.out.println("Time of Dispatch: "+rs.getTime("Time_Of_Dispatch"));
System.out.println("Location: "+rs.getString("Location"));
System.out.println();
}
}
} 출력
Connection established...... Product Name: KeyBoard Date of Dispatch: 1970-01-19 Time of Dispatch: 08:51:36 Location: Hyderabad Product Name: Earphones Date of Dispatch: 1970-01-19 Time of Dispatch: 05:54:28 Location: Vishakhapatnam Product Name: Mouse Date of Dispatch: 1970-01-19 Time of Dispatch: 04:26:38 Location: Vijayawada