JDBC Statement Interface
The Statement interface from java.sql enables the execution of static SQL queries on a database. The Statement interface handles basic SQL commands including SELECT, INSERT, UPDATE, and DELETE which do not require parameters.
Key Responsibilities
- Sending SQL queries to the database
- Executing read/write operations
- Fetching results using ResultSet
- Useful for simple and non-repetitive queries
Syntax
Statement stmt = connection.createStatement();
Methods of Statement
| Method | Description |
|---|---|
| executeQuery(String sql) | Executes a SELECT query and returns a ResultSet |
| executeUpdate(String sql) | Executes INSERT, UPDATE, or DELETE query; returns number of affected rows |
| execute(String sql) | Executes any SQL statement; returns boolean for result availability |
| close() | Closes the statement |
| getResultSet() | Returns the ResultSet from last execute() |
| getUpdateCount() | Returns number of rows affected |
Example
import java.sql.*;
public class StatementExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/testdb", "root", "password");
// Create statement
Statement stmt = con.createStatement();
// Execute query
ResultSet rs = stmt.executeQuery("SELECT * FROM employees");
// Process result
while (rs.next()) {
System.out.println(rs.getInt("id") + " " + rs.getString("name"));
}
// Close
rs.close();
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Statement vs PreparedStatement
| Feature | Statement | PreparedStatement |
|---|---|---|
| Query Type | Static (hardcoded) | Dynamic with parameters |
| Security | Vulnerable to SQL injection | Safe against SQL injection |
| Performance | Compiled every time | Precompiled — better for repeated use |
| Readability | Less readable for dynamic data | Clean and readable with parameter bindings |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.
point.com