How to Use PreparedStatement in Java?
A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of Statement. Prepared Statement objects have some useful additional features than Statement objects. Instead of hard coding queries, PreparedStatement object provides a feature to execute a parameterized query.
Advantages of PreparedStatement
- When PreparedStatement is created, the SQL query is passed as a parameter. This Prepared Statement contains a pre-compiled SQL query, so when the PreparedStatement is executed, DBMS can just run the query instead of first compiling it.
- We can use the same PreparedStatement and supply with different parameters at the time of execution.
- An important advantage of PreparedStatements is that they prevent SQL injection attacks.
Steps to use PreparedStatement
1. Create Connection to Database
Connection myCon = DriverManager.getConnection(path,username,password)
2. Prepare Statement
Instead of hardcoding queries like,
select * from students where age>10 and name ='Chhavi'
Set parameter placeholders(use question mark for placeholders) like,
select * from students where age> ? and name = ?
PreparedStatement myStmt; myStmt = myCon.prepareStatement(select * from students where age> ? and name = ?);
3. Set parameter values for type and position
4. Execute the Query
ResultSet myRs= myStmt.executeQuery();
Methods of PreparedStatement:
- setInt(int, int): This method can be used to set integer value at the given parameter index.
- setString(int, string): This method can be used to set string value at the given parameter index.
- setFloat(int, float): This method can be used to set float value at the given parameter index.
- setDouble(int, double): This method can be used to set a double value at the given parameter index.
- executeUpdate(): This method can be used to create, drop, insert, update, delete etc. It returns int type.
- executeQuery(): It returns an instance of ResultSet when a select query is executed.
Execute Query Example Code
Execute Update Example Code
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.