JDBC Callable statement provides a way to call the stored stored procedure of the database. These procedures stored in the database. This calls are written in escape syntax that may take one or two forms. The CallableStatement object is created by calling a prepareCall() method of connection;
CallableStatement cs = connection.prepareCall("CALL HI()");
A Simple Example of callable statement is give below which calls the stored procedure HI() from database student.
At first create a database student in MySql Then Create a Stored procedure in the database as
DELIMITER //
REATE PROCEDURE `HI`()
BEGIN
SELECT 'HI FRIEND !' AS MESSAGE;
END //
DELIMITER;
Now you call the stored procedure in your application as.
String query = "CALL HI()";
CallableStatement cs = connection.prepareCall(query);
CalllableStatement.java
package roseindia.net;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.swing.text.html.CSS;
public class CalllableStatement {
Connection connection = null;
public CalllableStatement() {
try {
// Loading the driver
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
System.out.println(e.toString());
}
}
// Creating a function to get a connection
public Connection createConnection() {
Connection con = null;
// checking connection
if (connection != null) {
System.out.println("Can't creaate a connection");
return connection;
} else {
try {
// Getting connection
con = DriverManager.getConnection(
"jdbc:mysql://localhost/student", "root",
"root");
} catch (Exception e) {
System.out.println(e.toString());
}
}
return con;
}
public static void main(String[] args) {
CalllableStatement calllableStatement = new CalllableStatement();
Connection connection = calllableStatement.createConnection();
try {
// Creating Callable Statement
String query = "CALL HI()";
CallableStatement cs = connection.prepareCall(query);
ResultSet rs = cs.executeQuery();
// checking result
if (rs == null) {
System.out.println("Result is null");
} else {
rs.next();
System.out.println(rs.getString("MESSAGE"));
connection.close();
}
} catch (Exception e) {
System.out.println(e.toString());
}
}
}
| HI FRIEND ! |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.