The JDBC (Java Database Connectivity) Statement interface provides a way to execute SQL statements and retrieve results from a database in Java. It belongs to the java.sql package and is commonly used for database interactions. Here's an example code snippet that demonstrates the usage of the JDBC Statement interface:
import java.sql.*;
public class JDBCStatementExample {
public static void main(String[] args) {
// Database connection parameters
String url = "jdbc:mysql://localhost:3306/mydatabase";
String username = "username";
String password = "password";
try {
// Step 1: Load and register the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Step 2: Establish the database connection
Connection connection = DriverManager.getConnection(url, username, password);
// Step 3: Create a Statement object
Statement statement = connection.createStatement();
// Step 4: Execute a SQL query
String sqlQuery = "SELECT * FROM customers";
ResultSet resultSet = statement.executeQuery(sqlQuery);
// Step 5: Process the query results
while (resultSet.next()) {
int id = resultSet.getInt("id");
String name = resultSet.getString("name");
String email = resultSet.getString("email");
System.out.println("ID: " + id + ", Name: " + name + ", Email: " + email);
}
// Step 6: Close the ResultSet, Statement, and Connection
resultSet.close();
statement.close();
connection.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Let's break down the code and explain each step:
-
First, we define the necessary database connection parameters: url, username, and password for connecting to the MySQL database.
-
We load and register the JDBC driver using Class.forName("com.mysql.cj.jdbc.Driver"). This step is specific to the database you are using, and it ensures that the appropriate driver class is available.
-
We establish a connection to the database using DriverManager.getConnection(url, username, password).
-
Next, we create a Statement object by calling connection.createStatement(). This object allows us to execute SQL statements on the database.
-
We execute a SQL query by calling statement.executeQuery(sqlQuery), passing in the SQL query as a string. In this example, we are selecting all records from the "customers" table.
-
The results of the query are stored in a ResultSet object. We can iterate over the result set using a while loop and retrieve the data using various getter methods (getInt(), getString(), etc.) based on the data types in the database.
-
We process and print the query results. In this example, we retrieve the "id," "name," and "email" columns for each row and display them on the console.
-
Finally, we close the ResultSet, Statement, and Connection objects to release the database resources.
Note that the code provided assumes the use of the MySQL database. If you are using a different database, you may need to modify the driver class and connection URL accordingly.