Types of Statements in JDBC

Types of Statements in JDBC

Java Database Connectivity (JDBC) provides a set of interfaces and classes to connect and execute queries on databases. To execute SQL queries using JDBC, one can utilize three types of statements:

  1. Statement
  2. PreparedStatement
  3. CallableStatement

Let's delve into each one:

1. Statement

The Statement interface is used to execute simple SQL queries without parameters.

Features:

  • Used for executing static SQL statements.
  • Every time a SQL query is executed, it is compiled by the DBMS.

Drawbacks:

  • Might have performance issues because the query is compiled every time it's executed.
  • Susceptible to SQL injection attacks.

Example:

Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users"); 

2. PreparedStatement

The PreparedStatement interface extends the Statement interface. It represents a precompiled SQL statement which can be executed multiple times without recompilation.

Features:

  • Can have one or more IN parameters.
  • Offers better performance than Statement because the query is compiled only once.
  • Prevents SQL injection attacks due to its inherent design of parameter binding.

Example:

String query = "INSERT INTO users (name, age) VALUES (?, ?)"; PreparedStatement pstmt = connection.prepareStatement(query); pstmt.setString(1, "John"); pstmt.setInt(2, 25); pstmt.executeUpdate(); 

3. CallableStatement

The CallableStatement interface is used to execute SQL stored procedures. Stored procedures are programs that are stored and executed on the database server.

Features:

  • Can return multiple results.
  • Can accept parameters.
  • Provides a way to access database-specific features and calls to database stored procedures.

Example:

// Assuming we have a stored procedure named "increaseSalary" in our database String procedure = "{CALL increaseSalary(?, ?)}"; CallableStatement cstmt = connection.prepareCall(procedure); cstmt.setInt(1, 1000); // assuming first parameter is an amount to increase cstmt.setInt(2, 5); // assuming second parameter is an employee id cstmt.execute(); 

Conclusion

When deciding which statement type to use in JDBC:

  • Use Statement for simple, static SQL statements without input parameters.
  • Use PreparedStatement for SQL queries that might be executed multiple times or have input parameters, especially when preventing SQL injection attacks is a concern.
  • Use CallableStatement when you need to work with SQL stored procedures.

Always ensure to close the statement (and associated result sets) after usage to release database resources. Consider using try-with-resources introduced in Java 7 to handle the auto-closing of these resources.


More Tags

monitoring contenttype formatexception cakephp-3.x zipcode kotlin caching isnumeric formgroups commando

More Programming Guides

Other Guides

More Programming Examples