How to Handle SQL Injection in JDBC using PreparedStatement?
Last Updated :
24 Apr, 2025
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 by using SQL injection.
To avoid this situation, we have one solution in JDBC with Java which is PreparedStatement.
Handle SQL injection using PreparedStatement
Now, we will explain how to prevent SQL injection in JDBC by using PreparedStatement.
This PreparedStatement can be able to allow us to write SQL statements in the form of placeholders, The placeholders always represented by using the symbol "?". For a better understanding of the concept, we will explain this with one example.
PreparedStatement syntax:
PreparedStatement preparedStatement = connection.prepareStatement(sql_query)
Note: While working with JDBC and MySQL you need to add mysql-connector jar file to your project.
Example to Handle SQL injection in JDBC Using PreparedStatement
In this example, we insert some rows in MySQL Database. For this first you need to create one database after that create one table in that database, for that we have created one database called books. In this Database, we create one table That is book, Now, we have provided the images for Table schema.

The above picture is help us to describe the table.
- In this Table, there is four fields namely id, author, name, price.
- Here the id is the primary key which auto increment also After that author field indicates name of the author.
- The name field indicates name of book, The final field is price is indicating price of the book.
In the below Java code, we have taken input from user after that we have inserted that data into Table.
Java
// Java Program to Handle SQL injection in
// JDBC Using PreparedStatement
package geeksforgeeks;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Random;
import java.util.Scanner;
// Driver Class
public class PreparedStatementExample {
public static int generateId() {
Random random = new Random();
int bookId = 1000 + random.nextInt(9000);
return bookId;
}
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/books", "root", "password");
Scanner input = new Scanner(System.in);
if (con != null) {
System.out.println("Enter Author Name");
String authorName = input.nextLine();
System.out.println("Enter Book Name");
String bookName = input.nextLine();
System.out.println("Enter Book Price");
String bookPrice = input.nextLine();
String insertQuery = "INSERT INTO book VALUES (?,?,?,?)";
PreparedStatement statement = con.prepareStatement(insertQuery);
statement.setInt(1, generateId());
statement.setString(2, authorName);
statement.setString(3, bookName);
statement.setString(4, bookPrice);
int rowsAffected = statement.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Record Inserted !...");
} else {
System.out.println("Record not Inserted !...");
}
// Close PreparedStatement and Connection
statement.close();
con.close();
} else {
System.out.println("Not Connected...");
}
} catch (Exception e) {
System.out.println("Exception is " + e.getMessage());
}
}
}
Output:

- After running this program, it will ask user inputs in the Java console.
- Like above picture once we provide all details the row is inserted into table you can observe the success message on the console.
Now we have provided picture for data in the table. Initially we have one row in database after we have inserted one more row. After this the output will look like below:

Explanation of the above Program:
- In the above code, we have created one generateId() for set id for each row while inserting.
- After that we have created required connection by using Connection class in Java.
- Then we provide some values for connection like Database name, username, password and others.
- After that we have taken inputs from user for inserting data into table by using PreparedStatement.
- After that we called executeUpdate() for save the data by using PreparedStatement object.
- Finally close the statement and connection.
Similar Reads
How to Perform a Bulk Insertion using JDBC?
Performing a bulk insert using JDBC involves using the PreparedStatement interface and addBatch() method. This addBatch() method increases the performance while data is inserted into a database. In this article, we will learn how to perform a bulk insert using JDBC. Approach:For this, we need to cre
4 min read
How to Retrieve Database Information using Database Meta Data in JDBC?
JDBC (Java Database Connectivity) is the standard Java API for connecting and interacting with relational databases. It allowed to the Java applications to execute the SQL queries, retrieve the results, and perform the operations of the database in programmatically. In this article, we will learn to
3 min read
How to use an ArrayList as a Prepared Statement Parameter?
ArrayList is part of the Java Collection Framework and In this article, we will learn how to use an ArrayList as a prepared statement parameter. Prepared StatementIt is a subinterface of the Statement interface. It is used to execute SQL parameterized queries and enhance performance and security. He
5 min read
Java Program to Insert Details in a Table using JDBC
Java Database Connectivity is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, Postgres, SQL, etc. It connects the front end(for interacting with the users ) with the backend( for storing data). Algorithm: Search/ Insert/ D
4 min read
How to Handle NULL Values in JDBC?
Java programming can be able to handle databases by using JDBC API. In this article, we will discuss how to handle NULL values in JDBC. For this problem, we have inserted some data into an already created table named book in my Database named books. To handle null values in JDBC involves checking fo
4 min read
How to Create a Statement Object in JDBC ?
JDBC stands for Java Database Connectivity. It is used in Java-based API which allows Java Applications to interact and perform operations on relational databases. Creating a "Statement" object in JDBC is an important step while dealing with a database in Java. A "Statement" object is used to execut
4 min read
How to Execute a SQL Script File using JDBC?
JDBC stands for Java Database Connectivity. It is an API (Application Programming Interface) that allows developers to connect their Java code to any SQL database instance. The connection gives the power to developers to execute any SQL queries, be it creating, updating, or data retrieving queries,
6 min read
Java Program to Delete a Column in a Table Using JDBC
Before deleting a column in a table, first is need to connect the java application to the database. Java has its own API which JDBC API which uses JDBC drivers for database connections. Before JDBC, ODBC API was used but it was written in C which means it was platform-dependent. JDBC API provides th
3 min read
How to Execute a SQL Query with Named Parameters in JDBC?
Executing the SQL (Structured Query Language) query with named parameters in JDBC (Java Database Connectivity) is the fundamental feature of the database interaction in Java. Named parameters provide convenient and it provides a secure way to pass the values into the SQL queries without using concat
4 min read
How to Execute a SQL Query Using JDBC?
Java programming provides a lot of packages for solving problems in our case we need to execute SQL queries by using JDBC. We can execute a SQL query in two different approaches by using PreparedStatement and Statement. These two interfaces are available in java.sql package. When comparing both of t
4 min read