×

Prepared statement in Java

Prepared statement:

A prepared statement is a statement that is pre-compiled SQL statement, and it is a sub-interface of a statement. Compared to other statement objects in java, Prepared Statement objects have some useful additional features.

Advantages of Prepared Statement

The prepared Statement is created when the SQL query is passed as a parameter.

we can use the same Prepared Statement and supply different parameters at the time of execution

The SQL injection attacks are prevented by prepared Statement.

Creating preparedStatement object:
PreparedStatement pstmt = null;
try {
   String SQL = "Update student SET dept = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   . . .
}

In JDBC, the parameters that are presented are represented by the symbol “?” which is also known as the parameter marker and before executing the sql statement we should supply value to every parameter.

Closing preparedStatement object:
PreparedStatement pstmt = null;
try {
   String SQL = "Update Student SET dept = ? WHERE id = ?";
   pstmt = conn.prepareStatement(SQL);
   . . .
}
catch (SQLException e) {
   . . .
}
finally {
   pstmt.close();
}

Example 1:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class TestApplication {
   static final String USER = "guest";
   static final String PASS = "guest123";
   static final String QUERY = "SELECT id,name, age FROM Employees";
   static final String UPDATE_QUERY = "UPDATE Employees set age=? WHERE id=?”;


   public static void main (String[] args) {   
// opening a connection 
   try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
         PreparedStatement stmt = conn.prepareStatement(UPDATE_QUERY);
      ) {       
         // Bind values into the parameters.
         stmt.setInt(1, 101);  // This would set age
         stmt.setInt(2, 102); // This would set ID
         int rows = stmt.executeUpdate();
         System.out.println("Rows impacted: " + rows );
         //select all the rows and display them
         ResultSet rs = stmt.executeQuery(QUERY);       


         // Extract data from result set
         while (rs.next()) {
            // Retrieve by column name
            System.out.print("ID: " + rs.getInt("id"));
            System.out.print(", Age: " + rs.getInt("age"));
            System.out.print(", Name: " + rs.getString("name"));
         }
         rs.close();
      } catch (SQLException e) {
         e.printStackTrace();
      } 
   }
}

Result:

Return value is : false
Rows impacted : 1
ID: 100, Age: 18, Name: Rani
ID: 101, Age: 25, Name: Raju
ID: 102, Age: 35, Name: Ramu
ID: 103, Age: 30, Name: Rahul

Example 2:

import java.sql.*;


public class jdbcConn {
   public static void main(String[] args) throws Exception {
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection ( 
         "jdbc:derby://localhost:1527/testDb","name","pass");
      PreparedStatement updateemp = con.prepareStatement(
         "insert into emp values(?,?,?)");
      
      updateemp.setInt(1,18);
      updateemp.setString(2,"Mounika");
      updateemp.setString(3, "Engineer");
      updateemp.executeUpdate();
      
      Statement stmt = con.createStatement();
      String query = "select * from emp";
      ResultSet rs =  stmt.executeQuery(query);
      System.out.println("Id Name    Job");
      
      while (rs.next()) {
         int id = rs.getInt("id");
         String name = rs.getString("name");
         String job = rs.getString("job");
         System.out.println(id + "  " + name+"   "+job);
      }      
   }
}

Output:

Id name job
18 Mounika Engineer

Difference between Statement and PreparedStatement : 
 

StatementPreparedStatement
When the SQL query is to be executed only once then it is used.SQL queries are executed multiple times.
we cannot pass the parameters at runtime.we can pass the parameters at runtime.
We can use it for CREATE, ALTER, DROP the statements.This are used for the queries which are to be executed multiple times.
Performance is very much low in statement.In prepared Statement performance is more better than Statement.
Statement is a base interface.It is used to extend the statement interface.
Normal SQL queries are executed in this statement.It used to execute dynamic SQL queries.
We cannot use statement for binary data reading.We can use Preparedstatement for binary data reading.
We can create DDL statements.We can create any SQL Query.
We cannot use statement for binary data writing.We can use Preparedstatement for binary data writing.
No binary protocol in the statement is used for communication.
Example:
//Creating Statement Object
Statement GFG = con.createStatement();

//Executing The Statement  GFG.executeUpdate("CREATE TABLE EMPLOYEE(ID NUMBER NOT NULL, NAME VARCHAR)");
Binary protocol in the preparedStatement is used for communication.
Example:
//Creating the PreparedStatement object PreparedStatement GFG = con.prepareStatement("update STUDENT set NAME = ? where ID = ?");

//Setting values to place holders 
//Assigns "RAM" to first place holder GFG.setString(1, "RAM");             

//Assigns "512" to second place holder GFG.setInt(2, 512);

//Executing PreparedStatement GFG.executeUpdate();                   

Related Topics

How to Convert int to char in Java

To convert a higher data type to lower data type, we need to do typecasting. Casting is also required when we want to convert ASCII value into character. It is...

3 minutes read.

Set Value to Enum in Java

In this article, you will be acknowledged about Enum in java. Most importantly you will learn how to set value to Enum or how to practically customize a value to...

3 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java Math cos() Method

The cos() method of Math class returns the trigonometric cosine of the specified angle. Syntax: public static double cos(double a) Parameters: The parameter ‘a’ represents an angle measured in radians. Return Value: The cos() method returns...

1 minute read.

How to Run Applet Program in Java

An applet is a new type of program which is put in a webpage. By inserting applet into a webpage dynamic content can be created. Characteristics of an Applet The applet is...

11 minutes read.

Program to find and replace characters on string in java

In JAVA, Strings are immutable. To overcome this Java String class contains a lot of methods to do operations on Strings. One such method is replace method. String Replace It returns a...

3 minutes read.

Delete a Cycle from a Linked List in Java

Assume a method detectAndRemoveLoop(), which examines if a given Linked List includes a loop and, if so, eliminates this Loop and returns true. This returns false if the list does...

7 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.

Java Programming certification

The most common technology utilized in the creation of applications is Java. People and businesses like it because it turns original ideas into useful software solutions. A Java programming certification can...

6 minutes read.

Differences between Lock and Monitor in Java Concurrency

In this tutorial, we will discuss the overview of Lock and Monitor and the differences between them. Introduction Java Concurrency is the ability to perform specific tasks at a time parallelly. The...

4 minutes read.

What are Array strings in Java?

In normal programming, An array is a group and a collection of identical forms of data that are stored in a sequential memory region and may be accessed using their...

4 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Java Math atan() Method

The atan() method of Math class computes the trigonometric Arc Tangent (inverse of tangent ) of an angle. The value returned is between -pi/2 to pi/2. Syntax: public static double atan(double a) Parameters: The...

2 minutes read.

Least Operator to Express Number in Java

In this article, we will learn about how to obtain a target number using a single number or a single integer by leveraging least operators in Java. There can be...

3 minutes read.

Java Math pow() Method

The pow() method of Math class returns the value of first argument raised to the power of second argument i.e. ab. Syntax: public static double pow(double a, double b) Parameters: The parameters ‘a’ and...

3 minutes read.

How to Convert double to int in Java

The double is a larger data type than int. When we assign a larger type value to a variable of smaller type, then we need to perform the explicit conversion....

2 minutes read.

Java Numbers

We use primitive data types like byte, int, long, double, etc to work with the numbers, When we need objects, we use wrapper class like Integer, Double, Long, Byte, etc....

2 minutes read.