Java jdbc examples for calling stored procedures mysql


Here is an example of how to call a stored procedure in MySQL using JDBC in Java:

  1. Create the stored procedure in MySQL.

Here is an example of a stored procedure that takes a single input parameter and returns a result set:

CREATE PROCEDURE get_employees_by_salary (IN salary DOUBLE)
    SELECT * FROM employees WHERE salary > salary;
  1. Call the stored procedure in Java.

Here is an example of how to call the "get_employees_by_salary" stored procedure from Java using JDBC:

// 1. Load the MySQL JDBC driver

// 2. Create a connection to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");

// 3. Prepare the stored procedure call
CallableStatement stmt = conn.prepareCall("{call get_employees_by_salary(?)}");
stmt.setDouble(1, 50000.0); // Set the input parameter value

// 4. Execute the stored procedure call
ResultSet rs = stmt.executeQuery();

// 5. Process the result set
while ( {
    System.out.println(rs.getString("name") + " earns $" + rs.getDouble("salary"));

// 6. Clean up resources

The code above does the following:

  1. Loads the MySQL JDBC driver.
  2. Creates a connection to the database.
  3. Prepares the stored procedure call by creating a CallableStatement object and setting the input parameter value.
  4. Executes the stored procedure call using the executeQuery() method of the CallableStatement object.
  5. Processes the result set returned by the stored procedure by iterating through the ResultSet object using a while loop.
  6. Cleans up the resources by closing the ResultSet, CallableStatement, and Connection objects.

Note that you may need to modify the connection URL and login credentials to match your MySQL database configuration.