Learn the difference between Statement and PreparedStatement in JDBC. Statement is used for static SQL queries, while PreparedStatement is used for dynamic and parameterized queries.
PreparedStatement :-
- PreparedStatement is used to execute parameterized SQL queries multiple times efficiently.
- It extends the Statement interface and executes a precompiled SQL statement.
- It accepts input parameters using placeholders (?).
- Since the query is precompiled, it offers better performance when executed repeatedly.
- It helps prevent SQL Injection attacks.
- The SQL query is provided at the time of PreparedStatement object creation.
- It is commonly used for INSERT, UPDATE, DELETE, and SELECT operations with dynamic values.
PreparedStatement ps =
con.prepareStatement("INSERT INTO Employee VALUES(?, ?)");
ps.setInt(1, 101);
ps.setString(2, "Santosh");
ps.executeUpdate();
Statement :-
- Statement is generally used for executing static SQL queries.
- It does not support input parameters.
- The SQL query is compiled and executed every time it runs.
- It is comparatively slower than PreparedStatement for repeated executions.
- It is often used for simple DDL operations such as CREATE, ALTER, and DROP.
- The Statement object is created without passing an SQL query.
- SQL query is supplied when calling methods such as execute(), executeQuery(), or executeUpdate().
Examples: Creating a table, Dropping a table, Altering a table, Executing one-time static queries, Database setup scripts, Schema creation
Statement stmt = con.createStatement();
stmt.executeUpdate("CREATE TABLE Employee(id INT, name VARCHAR(50))");
Use Cases of Statement in JDBC
Example: Create a Table Using Statement
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class CreateTableExample {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String username = "root";
String password = "root";
try {
// Load Driver
Class.forName("com.mysql.cj.jdbc.Driver");
// Create Connection
Connection con = DriverManager.getConnection(url, username, password);
// Create Statement
Statement stmt = con.createStatement();
// SQL Query
String query = "CREATE TABLE Employee(" +
"id INT PRIMARY KEY, " +
"name VARCHAR(50), " +
"salary DOUBLE)";
// Execute Query
stmt.executeUpdate(query);
System.out.println("Table created successfully.");
// Close Resources
stmt.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}