The Statement interface is an important part of JDBC used to execute SQL queries in a Java application. It helps in sending commands to the database and getting results.
In this chapter, you will learn about the Statement interface, its methods, and how to use it to execute SQL queries in Java.
The Statement interface provides methods to execute SQL queries with the database. It acts as a factory for ResultSet, which means it helps in retrieving data from the database.
It is mainly used to execute simple SQL queries like SELECT, INSERT, UPDATE, and DELETE.
To use the Statement interface in a Java program, we need to import it from the java.sql package.
Here is the syntax to import Statement interface:
Or we can use:
The following table lists the important methods of the Statement interface.
| Method | Description |
|---|---|
| public ResultSet executeQuery(String sql): | Executes a SELECT query and returns a ResultSet object. |
| public int executeUpdate(String sql): | Executes queries like INSERT, UPDATE, DELETE, CREATE, DROP, etc. |
| public boolean execute(String sql): | Executes SQL statements that may return multiple results. |
| public int[] executeBatch(): | Executes a batch of SQL commands. |
The Statement interface does not define commonly used constant fields like the Connection interface. It mainly provides methods to execute queries.
The following example demonstrates how to use the Statement interface to delete a record from a database.
Output:
1 records affected
Explanation:
This example shows how to use the Statement interface to execute SQL queries. Here, a delete query is executed, and the number of affected records is displayed.
We request you to subscribe our newsletter for upcoming updates.