JDBC Statement in Java: Creating Statements and Executing SQL Queries (Execute, ExecuteQuery, ExecuteUpdate)
JDBC Statement in Java
In JDBC, a Statement is an interface present in the java.sql package. It is used to send SQL queries from a Java program to a database server.
The implementation of the Statement interface is provided by the database vendor (such as MySQL, Oracle, PostgreSQL) inside the JDBC driver JAR file.
Creating a JDBC Statement
To create a JDBC Statement, a database connection is required.
- The Connection interface provides the createStatement() method.
- This method returns an object of a subclass of the Statement interface.
Method Syntax:
public Statement createStatement();
The returned Statement object is used to execute SQL queries on the database.
Executing SQL Queries Using Statement
The Statement interface provides different methods to execute SQL queries depending on the query type.
1️⃣ execute(String query)
- A generic method used to execute any type of SQL query.
- Can execute DDL, DML, and DQL queries.
Examples:
- CREATE TABLE (DDL)
- INSERT, UPDATE, DELETE (DML)
- SELECT (DQL)
Return Type:
- boolean (true if ResultSet is returned, false otherwise)
2️⃣ executeUpdate(String query)
Used to execute DML queries such as:
- INSERT
- UPDATE
- DELETE
Return Type:
- int → Number of rows affected
Example Use Case:
Used when updating records like employee salary, inserting new users, or deleting records.
3️⃣ executeQuery(String query)
- Used to execute DQL queries (SELECT statements only).
- Returns a ResultSet object.
Return Type:
- ResultSet
Example Use Case:
Used to fetch data from the database, such as employee details or product lists.
Closing JDBC Resources
To avoid memory leaks and database connection issues, JDBC resources must be closed properly.
Close the Statement using:
statement.close();
Close the Connection using:
connection.close();
Both close() methods are part of interfaces whose implementations are provided by the database vendor inside the JDBC driver JAR.
🔑 Key Points for Exams & Interviews
- Statement depends on Connection
- Vendor provides implementation via driver JAR
- execute() → any SQL
- executeUpdate() → DML queries
- executeQuery() → SELECT queries
- Always close Statement and Connection
Comments
Post a Comment