Java - JDBC - Statement Interface
The Statement interface in Java is used to execute SQL statements that do not have any parameters. It is part of the Java Database Connectivity (JDBC) API and provides methods for executing SQL queries and updates against a database.
Here are some key points about the Statement interface:
- It is used to execute SQL statements against a database.
- It is created by calling the createStatement() method on a Connection object.
- It can be used to execute queries that return a set of rows, as well as updates that modify the contents of the database.
- The execute() method is used to execute any SQL statement, and the executeQuery() method is used to execute a SELECT statement and return a ResultSet object.
- The executeUpdate() method is used to execute INSERT, UPDATE, or DELETE statements and returns the number of rows affected.
- The addBatch() method can be used to add multiple SQL statements to a batch for execution in a single round trip to the database.
- The close() method is used to release the resources used by the Statement object.
- The Statement interface is part of the java.sql package.
Here is an example of using the Statement interface to execute a simple SQL query:
import java.sql.*;
public class Example {
public static void main(String[] args) throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM customers");
while (rs.next()) {
System.out.println(rs.getString("name"));
}
rs.close();
stmt.close();
conn.close();
}
}
In this example, we create a Connection object to a MySQL database, and then create a Statement object using the createStatement() method. We then execute a SELECT statement using the executeQuery() method and iterate over the results using the next() method of the ResultSet object. Finally, we close the resources in reverse order of creation using the close() method.