Prepared Statement
You may have noticed that we did not use a prepared statement in the previous section.
That was the first and last time that you have seen a Statement
in this tutorial.
From now on we will always use prepared statements.
Why?
Because it has only advantages using a PreparedStatement
instead of a Statement
.
- They prevent SQL injection
- They allow batch execution of queries
- Code with parameters is easier to ready
- They are precompiled and allow caching on the database side.
- Speeds up communication through a non-SQL binary protocol
Read a more detailed explanation at Baeldung
A PreparedStatement
is retrieved from the Connection
the same way as a Statement
.
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PreparedStatementUsage {
static DataSource dataSource;
public static void main(String[] args) {
try /*(1)*/(Connection conn = dataSource.getConnection(); //(2)
PreparedStatement stmt = /*(3)*/ conn.prepareStatement(
/*(4)*/ "SELECT player_name FROM player WHERE id = ?")) {
stmt.setInt(1, 10); //(5)
ResultSet resultSet = stmt.executeQuery(); //(6)
// here comes more
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- Declare our try with resources block
- Retrieve a connection from our datasource
- Create a new prepared statement
- Define our query with a placeholder ->
id = ?
- Set the first parameter in our query to the value 10
- Execute the query
Let's go through it step by step.
- Declare our try with resources block
- Retrieve a connection from our datasource
- Create a new prepared statement
- Define our query with a placeholder ->
id = ?
- Set the first parameter in our query to the value 10
- Execute the query
Values in a prepared statement start with index 1. You will not have to set them in the correct order, but you have to set them all.