Prepared Statement
A PreparedStatement is an interface in JDBC that allows you to execute SQL queries more securely and efficiently. It is used to execute parameterized SQL queries, preventing SQL injection and improving performance, especially when executing the same query multiple times with different parameters.
Benefits of Prepared Statements
- Prevents SQL Injection:
- Prepared statements automatically escape user input, protecting against SQL injection attacks.
- Efficiency:
- SQL queries are precompiled, making repeated executions faster.
- Security:
- No need to manually handle input sanitization.
Creating and Using a Prepared Statement
Create a PreparedStatement
UseConnection.prepareStatement()
to create a prepared statement.String sql = "INSERT INTO users (name, age) VALUES (?, ?)"; PreparedStatement pstmt = conn.prepareStatement(sql);
2. **Set Parameters**
Use `setXXX()` methods to bind values to the placeholders (`?`).
```java
pstmt.setString(1, "John Doe");
pstmt.setInt(2, 30);
Execute the Query Use
executeUpdate()
for INSERT, UPDATE, or DELETE queries.pstmt.executeUpdate();
Close Resources Always close the
PreparedStatement
andConnection
to avoid resource leaks.pstmt.close(); conn.close();
Example: Using PreparedStatement to Insert Data
import java.sql.*;
public class PreparedStatementExample {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password");
String sql = "INSERT INTO users (name, age) VALUES (?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, "Alice");
pstmt.setInt(2, 25);
pstmt.executeUpdate();
System.out.println("Data inserted successfully!");
pstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}