Show List
Prepared Statements and Callable Statements
Prepared Statements and Callable Statements are two different ways to execute SQL statements in Java Database Connectivity (JDBC).
A Prepared Statement is an SQL statement that is precompiled and stored in a database. When executed, the statement is parsed, optimized, and compiled just once, and then can be executed multiple times with different parameter values.
Example:
String sql = "INSERT INTO employees (id, first_name, last_name) VALUES (?,?,?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, 1);
statement.setString(2, "John");
statement.setString(3, "Doe");
statement.executeUpdate();
A Callable Statement is a stored procedure that can be called from a JDBC application. Callable statements are used to call stored procedures in a database.
Example:
String sql = "{call getEmpName(?,?)}";
CallableStatement statement = connection.prepareCall(sql);
statement.setInt(1, 1);
statement.registerOutParameter(2, Types.VARCHAR);
statement.execute();
String name = statement.getString(2);
Both Prepared Statements and Callable Statements can improve the performance and security of JDBC applications as compared to executing dynamic SQL statements, and are widely used in real-world applications.
Leave a Comment