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:
Let's delve into each one:
The Statement interface is used to execute simple SQL queries without parameters.
Features:
Drawbacks:
Example:
Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM users"); The PreparedStatement interface extends the Statement interface. It represents a precompiled SQL statement which can be executed multiple times without recompilation.
Features:
Statement because the query is compiled only once.Example:
String query = "INSERT INTO users (name, age) VALUES (?, ?)"; PreparedStatement pstmt = connection.prepareStatement(query); pstmt.setString(1, "John"); pstmt.setInt(2, 25); pstmt.executeUpdate();
The CallableStatement interface is used to execute SQL stored procedures. Stored procedures are programs that are stored and executed on the database server.
Features:
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(); When deciding which statement type to use in JDBC:
Statement for simple, static SQL statements without input parameters.PreparedStatement for SQL queries that might be executed multiple times or have input parameters, especially when preventing SQL injection attacks is a concern.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.
monitoring contenttype formatexception cakephp-3.x zipcode kotlin caching isnumeric formgroups commando