Open In App

How to Use PreparedStatement in Java?

Last Updated : 13 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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 

myStmt.setInt(1,10);     
myStmt.setString(2,"Chhavi");      

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.
Initial Table content

Original Table

Execute Query Example Code

Java




// Java program to execute a query using PreparedStatement
 
import java.sql.*;
 
public class GFG {
 
    // Driver Code
    public static void main(String[] args) throws Exception
    {
 
        // Register Driver Class
        Class.forName("org.apache.derby.jdbc.ClientDriver");
 
        // Connection to your database
        Connection con = DriverManager.getConnection();
 
        // Query which needs parameters
        String query
            = "Select * from students where age> ? and name = ?";
 
        // Prepare Statement
        PreparedStatement myStmt
            = con.prepareStatement(query);
 
        // Set Parameters
        myStmt.setInt(1, 20);
        myStmt.setString(2, 'Prateek');
 
        // Execute SQL query
        ResultSet myRs = myStmt.executeQuery();
 
        System.out.println('Age      Name');
 
        // Display function to show the Resultset
        while (myRs.next()) {
            String Name = rs.getString("name");
            int age = rs.getInt("age");
            System.out.println(Name + "     " + age);
        }
 
        // Close the connection
        con.close();
    }
}


 
 

Execute a Query using preparedstatement

Output

Execute Update Example Code 

Java




// Java program to update a table using PreparedStatement
 
import java.sql.*;
 
public class GFG {
 
    // Driver Code
    public static void main(String[] args) throws Exception
    {
 
        // Register Driver Class
        Class.forName("org.apache.derby.jdbc.ClientDriver");
 
        // Connection to your database
        Connection con = DriverManager.getConnection();
 
        // Query which needs parameters
        String query = "insert into Students values(?,?)";
 
        // Prepare Statement
        PreparedStatement myStmt
            = con.prepareStatement(query);
 
        // Set Parameters
        myStmt.setInt(1, 21);
        myStmt.setString(2, 'Prajjwal');
 
        // Execute SQL query
        int res = myStmt.executeUpdate();
 
        // Display the records inserted
        System.out.println(res + " records inserted");
 
        // Close the connection
        con.close();
    }
}


 
 

Update table using PreparedStatement Query

Output 

Table content after updation

Table After Inserting Values

 



Similar Reads

How to Handle SQL Injection in JDBC using PreparedStatement?
In this article, we can learn how to prevent SQL injection in JDBC by using Java programming. Basically, SQL injection is a type of security vulnerability It occurs when hackers or attackers can change or manipulate the SQL query, and this can lead to unauthorized access to resources and also perform different malicious activities once get access b
4 min read
Difference Between java.sql.Time, java.sql.Timestamp and java.sql.Date in Java
Across the software projects, we are using java.sql.Time, java.sql.Timestamp and java.sql.Date in many instances. Whenever the java application interacts with the database, we should use these instead of java.util.Date. The reason is JDBC i.e. java database connectivity uses these to identify SQL Date and Timestamp. Here let us see the differences
7 min read
How to Use Weka Java API?
To use the weka API you need to install weka according to your operating system. After downloading the archive and extracting it you’ll find the weka.jar file. The JAR file contains all the class files required i.e. weka API. Now we can find all the information about the classes and methods in the Weka Java API documentation. We need to add this ja
2 min read
When to use Rope over StringBuilder in Java?
What are Ropes? Rope is a binary tree data structure where each node except the leaf contains the number of characters present to the left of the node. They are mainly used by text editors to store and manipulate large strings. It provides different string operations such as append, insert and delete in a faster and more efficient way. Ropes work m
3 min read
How to Use Enumeration to Display Elements of Hashtable in Java?
Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. Now here we can get the keys and values of a Hashtable as an Enumeration object us
2 min read
Java Program to Use Exceptions with Thread
Exceptions are the events that occur due to the programmer error or machine error which causes a disturbance in the normal flow of execution of the program. When a method encounters an abnormal condition that it can not handle, an exception is thrown as an exception statement. Exceptions are caught by handlers(here catch block). Exceptions are caug
5 min read
Java Program to Illustrate Use of Binary Literals
A binary literal is a number that is represented in 0s and 1s (binary digits). Java allows you to express integral types (byte, short, int, and long) in a binary number system. To specify a binary literal, add the prefix 0b or 0B to the integral value. So, we can express binary digits in a program by assigning them to variables, and the output of t
3 min read
Java Program to use Catch to Handle the Exception
The exception is the event occurs when the program is executing. Due to this exception, the normal flow of the program will get disrupts. Whenever an exception occurs in the method, the method creates an object and sends that object to the runtime system. For example, the file needs to be open is not found, class not found exception, Arithmetic Exc
3 min read
Java Program to Use finally block for Catching Exceptions
The finally block in java is used to put important codes such as clean up code e.g. closing the file or closing the connection. The finally block executes whether exception rise or not and whether exception handled or not. A finally contains all the crucial statements regardless of the exception occurs or not. There are 3 possible cases where final
3 min read
Java Program to illustrates Use of Static Inner Class
Inner class means one class that is a member of another class. There are basically four types of inner classes in java. Nested Inner classMethod Local inner classesAnonymous inner classesStatic nested classesJava also allows a class to be defined within another class. These are called Nested Classes. The class in which the nested class is defined i
2 min read
Article Tags :
Practice Tags :