Java jdbc examples for calling stored procedures mysql
www.ieditfiga.com
Here is an example of how to call a stored procedure in MySQL using JDBC in Java:
- 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) BEGIN SELECT * FROM employees WHERE salary > salary; END
- 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 Class.forName("com.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 (rs.next()) { System.out.println(rs.getString("name") + " earns $" + rs.getDouble("salary")); } // 6. Clean up resources rs.close(); stmt.close(); conn.close();
The code above does the following:
- Loads the MySQL JDBC driver.
- Creates a connection to the database.
- Prepares the stored procedure call by creating a CallableStatement object and setting the input parameter value.
- Executes the stored procedure call using the executeQuery() method of the CallableStatement object.
- Processes the result set returned by the stored procedure by iterating through the ResultSet object using a while loop.
- 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.