×

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

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java Solid Principles

Java implements the object-oriented SOLID principles for the design of software architecture. Solid Principles Java implements the object-oriented SOLID principles for the design of software architecture.   Five guiding principles transformed...

4 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Java Boyer Moore

A string searching or matching technique called the Boyer-Moore algorithm was created in 1977 by Robert S. Boyer and J. Strother Moore. It is the most popular and effective string-matching...

9 minutes read.

Java Session

Session indicates interval of time. A session is a simple  time interval in which servers and client interacts. To maintain the state of the client or user we use technologies...

5 minutes read.

Compile-time Error in Java

In java, the execution of a program is stopped due to the occurrence of some problem known as an error. Errors are illegal operations that are carried out by the...

4 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Finding Odd Occurrence of a Number in Java

In this tutorial, we will learn how to find the odd occurrence of a number through a java program. Let us consider an array of non-negative integers. Here, except for one...

6 minutes read.

Program to check whether a given character is present in a string or not

In this article, you will understand the logic to find out whether the given character is present in the string or not and find out the position of the specified...

3 minutes read.

Java File

Java file class implements the concept of file handling. It has several methods, such as deleting, creating, reading, and updating files. This class allows java users to perform various operations...

5 minutes read.

Java Math log1p() Method

The log1p() method of Math class returns the natural logarithmic sum for the specified double argument and 1. Its value is much closer to result of ln(1 + x). Syntax: public static...

2 minutes read.

Majority Element in Java

It's an extremely intriguing question that is commonly asked in job interviews at prestigious IT firms like The Google, Amazon, TCS, and The Accenture, etc. By figuring out the solution, one may...

10 minutes read.

For Loop Program in Java

For Loop Program in Java The for-loop program in Java is written when we want a particular set of statements to be executed repeatedly until the given criteria/ condition is met....

8 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Array and String based questions in Java

1. What is an Array in Java? A collection of identical data types is referred to as an array. There can be no separate data kinds. It supports the storage of...

4 minutes read.

How to Convert String to boolean in Java

How to Convert String to boolean in Java There are two methods to convert String to boolean: Using parseBoolean(string) method Using valueOf(string) method If the string contains "True," "true," or "TRUE,"...

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.

Minimum Number of Taps to Open to Water a Garden in Java

Problem Statement The issue is that a gardener wants to water a (single-dimensional) garden using the fewest possible tap openings. The goal is to determine the minimum necessary taps to be...

8 minutes read.