This example show you how to call a stored procedure that return a result set of the query execution result.
package org.kodejava.jdbc;
import java.math.BigDecimal;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CallableStatementExample {
private static final String URL = "jdbc:mysql://localhost/kodejava";
private static final String USERNAME = "root";
private static final String PASSWORD = "";
public static void main(String[] args) {
try (Connection connection =
DriverManager.getConnection(URL, USERNAME, PASSWORD)) {
// Prepares a call to the sored procedure. This SP takes
// one IN parameter
String query = "call Get_Product_By_Price(?)";
CallableStatement cb = connection.prepareCall(query);
// Sets the input parameter
cb.setBigDecimal(1, new BigDecimal("50.99"));
// Execute the query
ResultSet rs = cb.executeQuery();
while (rs.next()) {
System.out.println("Product: " + rs.getString(1));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Here is the stored procedure script we use in the example above.
DELIMITER ;;
DROP PROCEDURE IF EXISTS Get_Product_By_Price;;
CREATE PROCEDURE Get_Product_By_Price(IN product_price DECIMAL(10, 2))
BEGIN
SELECT name FROM products WHERE price = product_price;
END;;
DELIMITER ;
Maven dependencies
<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.28/mysql-connector-java-8.0.28.jar -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.28</version>
</dependency>
Latest posts by Wayan (see all)
- How do I convert Map to JSON and vice versa using Jackson? - June 12, 2022
- How do I find Java version? - March 21, 2022
- How do I convert CSV to JSON string using Jackson? - February 13, 2022