Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

PreparedStatement, CallableStatement, and ResultSet


In advanced Java, managing database interactions is a crucial task. The JDBC (Java Database Connectivity) API provides various classes that simplify interacting with databases. Three important classes in JDBC are PreparedStatement, CallableStatement, and ResultSet, which allow developers to execute SQL queries, call stored procedures, and handle results efficiently. In this article, we will explore these classes and demonstrate their use through examples.

1. Introduction to PreparedStatement

The PreparedStatement is an extension of the Statement interface in JDBC. It is used to execute precompiled SQL queries with or without input parameters. Prepared statements help prevent SQL injection attacks and improve performance when executing the same query multiple times with different parameters.

Example: Using PreparedStatement for SQL Queries

            
            import java.sql.*;

            public class PreparedStatementExample {
                public static void main(String[] args) {
                    String url = "jdbc:mysql://localhost:3306/yourdatabase";
                    String user = "root";
                    String password = "password";

                    Connection conn = null;
                    PreparedStatement pstmt = null;
                    ResultSet rs = null;

                    try {
                        // Establish the connection
                        conn = DriverManager.getConnection(url, user, password);

                        // Create the SQL query
                        String sql = "SELECT * FROM employees WHERE salary > ?";
                        pstmt = conn.prepareStatement(sql);

                        // Set the parameter for salary
                        pstmt.setDouble(1, 50000.0);

                        // Execute the query
                        rs = pstmt.executeQuery();

                        // Process the result set
                        while (rs.next()) {
                            int id = rs.getInt("id");
                            String name = rs.getString("name");
                            double salary = rs.getDouble("salary");
                            System.out.println(id + ", " + name + ", " + salary);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (rs != null) rs.close();
                            if (pstmt != null) pstmt.close();
                            if (conn != null) conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            
        

In this example, we use PreparedStatement to execute a query that selects employees with a salary greater than a specified value. The query is precompiled, and the parameter is set using setDouble() to insert the salary value safely into the SQL query.

2. Introduction to CallableStatement

The CallableStatement interface is used to execute SQL stored procedures. It allows you to call stored procedures that may have input and output parameters. This is especially useful for executing complex SQL queries or database logic encapsulated in stored procedures.

Example: Using CallableStatement to Call a Stored Procedure

            
            import java.sql.*;

            public class CallableStatementExample {
                public static void main(String[] args) {
                    String url = "jdbc:mysql://localhost:3306/yourdatabase";
                    String user = "root";
                    String password = "password";

                    Connection conn = null;
                    CallableStatement cstmt = null;

                    try {
                        // Establish the connection
                        conn = DriverManager.getConnection(url, user, password);

                        // Create the SQL query to call a stored procedure
                        String sql = "{CALL getEmployeeById(?)}";
                        cstmt = conn.prepareCall(sql);

                        // Set the input parameter (employee ID)
                        cstmt.setInt(1, 1);

                        // Execute the stored procedure
                        ResultSet rs = cstmt.executeQuery();

                        // Process the result set
                        while (rs.next()) {
                            int id = rs.getInt("id");
                            String name = rs.getString("name");
                            double salary = rs.getDouble("salary");
                            System.out.println(id + ", " + name + ", " + salary);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (cstmt != null) cstmt.close();
                            if (conn != null) conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            
        

In this example, we use CallableStatement to call a stored procedure named getEmployeeById which retrieves an employee's details based on their ID. The input parameter (employee ID) is set using setInt() and passed to the stored procedure.

3. Introduction to ResultSet

The ResultSet object is used to store the results of a query. It provides methods for retrieving data from the result set, such as getString(), getInt(), getDouble(), etc. The result set is a cursor that points to the current row of the results, and you can iterate through the rows using methods like next().

Example: Using ResultSet to Retrieve Data

            
            import java.sql.*;

            public class ResultSetExample {
                public static void main(String[] args) {
                    String url = "jdbc:mysql://localhost:3306/yourdatabase";
                    String user = "root";
                    String password = "password";

                    Connection conn = null;
                    Statement stmt = null;
                    ResultSet rs = null;

                    try {
                        // Establish the connection
                        conn = DriverManager.getConnection(url, user, password);

                        // Create the SQL statement
                        String sql = "SELECT * FROM employees";
                        stmt = conn.createStatement();

                        // Execute the query
                        rs = stmt.executeQuery(sql);

                        // Process the result set
                        while (rs.next()) {
                            int id = rs.getInt("id");
                            String name = rs.getString("name");
                            double salary = rs.getDouble("salary");
                            System.out.println(id + ", " + name + ", " + salary);
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } finally {
                        try {
                            if (rs != null) rs.close();
                            if (stmt != null) stmt.close();
                            if (conn != null) conn.close();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            
        

In this example, we use ResultSet to retrieve data from the employees table. We execute a simple SQL query, and then iterate over the result set using next() to print each employee's details.

4. Summary of Differences

Here’s a quick summary of the differences between PreparedStatement, CallableStatement, and ResultSet:

5. Conclusion

In this article, we have explored the usage of PreparedStatement, CallableStatement, and ResultSet in advanced Java for database interaction. These JDBC components play a key role in executing SQL queries, calling stored procedures, and managing the result sets. Understanding how to use these classes effectively will allow you to write efficient, secure, and maintainable database code in Java applications.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java