![]() |
VOOZH | about |
In JDBC (Java Database Connectivity), Statement objects are used to send SQL commands to a database and process the results. JDBC provides various types of statements to execute SQL queries efficiently, tailored to the applicationโs specific needs.
There are three main types of statements in JDBC:
A Statement object is used for general-purpose access to databases and is useful for executing static SQL statements at runtime.
Syntax:
Statement statement = connection.createStatement();
Example: Java Program illustrating Statement in JDBC
Output: Name and age are as shown for random inputs.
๐ Output of Create Statement
A PreparedStatement is a precompiled SQL statement. It supports parameters (?) which can be set dynamically, making it faster and safer than Statement.
Syntax:
String query = "INSERT INTO people(name, age) VALUES (?, ?)";
PreparedStatement pstmt = con.prepareStatement(query);
Example: Java Program illustrating Prepared Statement in JDBC
Output:
๐ Output of Prepared Statement
A CallableStatement is used to execute stored procedures in the database. Stored procedures are precompiled SQL logic stored on the server, often used for complex operations.
Syntax:
CallableStatement cstmt = con.prepareCall("{call ProcedureName(?, ?)}");
Example: Java Program illustrating Callable Statement in JDBC
Output:
๐ Output for Callable Statement
| Feature/Aspect | Statement | PreparedStatement | CallableStatement |
|---|---|---|---|
| Purpose | Used for executing simple/static SQL queries | Used for executing parameterized SQL queries | Used for executing stored procedures |
| SQL Reusability | SQL query written directly inside executeQuery() or executeUpdate() | SQL query is precompiled and stored; can be executed multiple times with different parameters | Calls stored procedures that may contain multiple SQL statements |
| Parameters Support | Not supported (values must be hard-coded in query) | Supported using ? placeholders | Supported using ? placeholders for IN, OUT and INOUT parameters |
| Performance | Slower for repeated queries (query compiled each time) | Faster for repeated queries (query compiled once and reused) | Efficient when using stored procedures, since logic is precompiled in DB |
| Security (SQL Injection) | Vulnerable to SQL injection if user input is concatenated directly into query | Prevents SQL injection (parameters are bound safely) | Prevents SQL injection (parameters are bound safely) |
| Return Type | Returns single/multiple ResultSet or update count | Returns single/multiple ResultSet or update count | Returns single/multiple ResultSet, update count and can handle output parameters |