package task9; import java.sql.Connection; import java.sql.DriverManager; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.SQLException; public class callablefunctions { // Database credentials and URL static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name static final String JDBC_USER = "root"; // Replace with your MySQL username static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password public static void main(String[] args) { // SQL query to call the stored function String callFunctionSQL = "{? = call getAverageAgeByGrade(?)}"; try (Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); CallableStatement callableStatement = connection.prepareCall(callFunctionSQL)) { // Register the output parameter (the average age) callableStatement.registerOutParameter(1, java.sql.Types.DOUBLE); // Set the input parameter (the grade for which we want the average age) callableStatement.setString(2, "A"); // Change the grade as needed // Execute the function callableStatement.execute(); // Retrieve the output parameter double averageAge = callableStatement.getDouble(1); System.out.println("Average age of students with grade 'A': " + averageAge); } catch (SQLException e) { System.out.println("SQL Exception: " + e.getMessage()); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter