PreparedStatement is an Interface in java.sql package and allows Java programmer to execute SQL queries by using JDBC package. You can get PreparedStatement object by calling Connection.prepareStatement() method.SQL queries passed to this method goes to Database for pre-compilation if JDBC driver supports it. If it doesn’t, than pre-compilation occurs when you execute prepared queries. Prepared Statement queries are pre-compiled on database and there access plan will be reused to execute further queries which allows them to execute much quicker than normal queries generated by Statement object. Here is an example of how to use PreparedStatement in Java:
public class PreparedStmtExample {
public static void main(String args[]) throws SQLException {
Connection conn = DriverManager.getConnection("jdbc:mysql:\\localhost:3306", "root","");
PreparedStatement preStatement = conn.prepareStatement("select distinct loan_type from loan where bank=?");
preStatement.setString(1, "Citibank");
ResultSet result = preStatement.executeQuery();
while(result.next()){
System.out.println("Loan Type: " + result.getString("loan_type"));
}
}
}
Output:
Loan Type: Personal Loan
Loan Type: Auto Loan
Loan Type: Home Loan
Loan Type: Gold Loan
In this example of PreparedStatement same query and access path will be used. If you pass a different parameter e.g. “Standard Charted” or “HSBC”.
ResultSet returned by prepared statement execution is of “TYPE_FORWARD_ONLY” but can be customized by using overloaded method of prepareStatement().
Benefits of Java Prepared Statement:
PreparedStatement in Java JDBC offers several benefits and it’s a recommended way to execute SQL queries in any enterprise Java application or in production code. Here are few advantages of using PreparedStatement in Java:
1. PreparedStatement allows you to write dynamic and parametric query.
By using PreparedStatement in Java you can write parametrized sql queries and send different parameters by using same sql queries which is lot better than creating different queries. Here is an example of parametric query written using PreparedStatement in java:
select interest_rate from loan where loan_type=?
Now you can run this query for any loan type e.g. “personal loan”, “home loan” or “gold loan”. This example of SELECT query is called parametric or parametrized query because it can be invoked with different parameter. Here “?” is used as place holder for parameter.
2. PreparedStatement is faster than Statement in Java
One of the major benefits of using PreparedStatement is better performance. PreparedStatement gets pre compiled
In database and there access plan is also cached in database, which allows database to execute parametric query written using prepared statement much faster than normal query because it has less work to do. You should always try to usePreparedStatement in production JDBC code to reduce load on database. In order to get performance benefit its worth noting to use only parametrized version of sql query and not with string concatenation. Out of following two examples of SELECT queries, first example of SELECT query will not offer any performance benefit:
SQL Query 1: PreparedStatement with String concatenation
String loanType = getLoanType();
PreparedStatement prestmt = conn.prepareStatement("select banks from loan where loan_type="+ loanType);
SQL Query 2: Parameterized query using PreparedStatement
PreparedStatement prestmt = conn.prepareStatement("select banks from loan where loan_type=?");
prestmt.setString(1,loanType);
Second SQL query is correct use of PreparedStatement in Java and give better performance than SQL query1.
3. PreparedStatement prevents SQL Injection attacks in Java
If you have been working in Java web application you must be familiar with infamous SQL Injection attacks, last year Sony got victim of SQL injection and compromised several Sony play station user data. In SQL Injection attack, malicious user pass SQL meta-data combined with input which allowed them to execute sql query of their choice, If not validated or prevented before sending query to database. By using parametric queries and PreparedStatement you prevent many forms of SQL injection because all the parameters passed as part of place-holder will be escaped automatically by JDBC Driver. Though It’s worth remembering that in above example of two PreparedStatement only second example will prevent SQL injection attacks and first example is not secure with SQL injection.
4. At last PreparedStatement queries are more readable and secure than cluttered string concatenated queries.