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 optimized for basic learning, practice and more. Examples are well checked and working examples available on this website but we can't give assurity for 100% correctness of all the content. This site under copyright content belongs to Onlinetpoint. You agree to have read and accepted our terms of use, cookie and privacy policy.