Use the PreparedStatement class rather than doing manual checking. This means that the driver will automatically escape the string you give it and a SQL injection attempt will fail and whatever data they provide will be passed into the database field. See https://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html and https://docs.oracle.com/javase/8/docs/api/java/sql/PreparedStatement.html for more details on how to use it.

To get a parameter that has been sent you can use

// create connection
String passed = request.getParameter("data");
PreparedStatement statement = connection.prepareStatement("INSERT INTO table (field1) VALUES (?)");
statement.setString(1, passed);
statement.executeQuery();
Answer from Jonathan Coustick on Stack Overflow
🌐
DigitalOcean
digitalocean.com › community › tutorials › sql-injection-in-java
SQL Injection in Java and How to Easily Prevent it | DigitalOcean
August 3, 2022 - A hacker can alter user requests using tools like Postman, cURL, etc. to send SQL code as data and this way bypassing any UI side validations. ... Result: Now the above query is having two conditions with SQL OR expression. userId=2: This part will match table rows having userId value as ‘2’. 1=1: This part will be always evaluate as true. So Query will return all the rows of the table. Let’s look at the four types of SQL injections.
Discussions

SQL Injection in Java and How to Easily Prevent it
Explore the insidious threat of SQL Injection in Java applications and learn how to fortify your code against this malicious exploit. More on accuweb.cloud
🌐 accuweb.cloud
1
December 1, 2023
Java - escape string to prevent SQL injection - Stack Overflow
I'm trying to put some anti sql injection in place in java and am finding it very difficult to work with the the "replaceAll" string function. Ultimately I need a function that will convert any exi... More on stackoverflow.com
🌐 stackoverflow.com
java - How to detect SQL injection attempt - Stack Overflow
However, I want to do some security logs each time someone attempts an SQL injection. I have a Java input string on back-end, how can I detect when someone tries an injection? I tried some regex but without success. ... What is the point? If your code is using prepared statement and parameters, ... More on stackoverflow.com
🌐 stackoverflow.com
mysql - Prevent SQL injection attacks in a Java program - Stack Overflow
I heard that this can be exploited through an SQL injection like: ... My program has a Java GUI and all name, address and email values are retrieved from Jtextfields. I want to know how the following code (DROP TABLE customer;) could be added to my insert statement by a hacker and how I can ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
OWASP Cheat Sheet Series
cheatsheetseries.owasp.org › cheatsheets › SQL_Injection_Prevention_Cheat_Sheet.html
SQL Injection Prevention - OWASP Cheat Sheet Series
A common SQL injection flaw in Java is shown below. Because its unvalidated "customerName" parameter is simply appended to the query, an attacker can enter SQL code into that query and the application would take the attacker's code and execute it on the database.
🌐
DZone
dzone.com › coding › languages › how to check text inputs for sql injection attacks in java
How to Check Text Inputs for SQL Injection Attacks in Java
April 25, 2021 - Detection level (optional): threat detection level for the process; set to Normal to target a high-security SQL Injection detection level with a very low false-positive rate; select High to target a very-high security SQL Injection detection level with higher false positives. Default is Normal (recommended). We can input the above information into the following code to call our validation function:
🌐
Baeldung
baeldung.com › home › persistence › sql injection and how to prevent it?
SQL Injection and How to Prevent It? | Baeldung
March 18, 2026 - Some also include in-JVM agents that can detect intrusions by applying some instrumentation – the main advantage of this approach is that an eventual vulnerability becomes much easier to fix since we’ll have a full stack trace available. In this article, we’ve covered SQL Injection vulnerabilities in Java applications – a very serious threat to any organization that depends on data for their business – and how to prevent them using simple techniques. The code ...
🌐
W3Schools
w3schools.com › sql › sql_injection.asp
SQL Injection
The next chapters show the most effective methods to prevent SQL injections, using SQL Parameters and SQL Prepared Statements. Look at the example above again. The original purpose of the SQL code was to select a user with a given user id.
🌐
StackHawk
stackhawk.com › stackhawk, inc. › vulnerabilities and remediation › preventing sql injection in java
Preventing SQL Injection in Java
January 10, 2025 - Well, technically speaking, there’s no such thing as a “Java SQL injection.” When we say that, we’re simply referring to SQL injection attacks to Java codebases.
Find elsewhere
🌐
Bright Security
brightsec.com › blog › sql-injection-in-java
SQL Injection in Java and how to easily prevent it - Bright Security
August 10, 2025 - Java Persistence API adds an extra data layer for apps, and helps limit an attacker’s ability to use and leverage SQL injections. Bright helps automate the detection and remediation of many vulnerabilities including SQL Injection, early in the development process.
🌐
GitHub
github.com › rkpunjal › sql-injection-safe › blob › master › src › main › java › com › github › rkpunjal › sqlsafe › SqlSafeUtil.java
sql-injection-safe/src/main/java/com/github/rkpunjal/sqlsafe/SqlSafeUtil.java at master · rkpunjal/sql-injection-safe
import java.util.regex.Pattern; · · /** · * <h2>SqlSafeUtil</h2> · * Util Class to help verify if provided string value is sql injection safe · * · * @author Ramakrishna Punjal · * @version 1.0.0 · * @since 2016-08-26 · * · */ ·
Author   rkpunjal
🌐
SecureFlag
knowledge-base.secureflag.com › vulnerabilities › sql_injection › sql_injection_java.html
SQL Injection in Java | SecureFlag Security Knowledge Base
August 5, 2025 - For example, by injecting 123 OR 1=1;-- in the id field, the SQL query becomes: SELECT account_number, account_balance FROM customer_data WHERE account_owner_id = 123 OR 1=1;-- The manipulated query returns any entry in the customer_data table with an owner ID of 123 or if 1 equals 1. The query statement is then terminated by commenting out any trailing code using ;--. Since the WHERE statement is always true, the query returns all of the orders of all of the customers.
🌐
Accuweb
accuweb.cloud › home › sql injection in java and how to easily prevent it
SQL Injection in Java and How to Easily Prevent it - AccuWeb Cloud
December 1, 2023 - It then authenticates the user by querying the database using a prepared statement, which prevents SQL Injection. Feel free to use this example as a reference while ensuring that you have configured your database connection properly, and replace your_db_username and your_db_password with your actual database credentials. ... import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class SecureDatabaseAccess { public static void main(String[] args) { String jdbcUrl = "jdbc:mysql://localhost:3306/userdb"; String dbUser = "your_db_username"; String dbPassword = "your_db_password"; String userInput = "alice' OR '1'='1"; if (!isValidInput(userInput)) { System.out.println("Invalid input.
🌐
GeeksforGeeks
geeksforgeeks.org › java › understanding-and-preventing-sql-injection-in-java-applications
Understanding and Preventing SQL Injection in Java Applications - GeeksforGeeks
October 24, 2023 - Input Encoding: Encode special ... as SQL code. SQL injection is a severe security threat that can lead to data breaches and system compromise. Protecting your Java applications from SQL injection is paramount. By using prepared statements and parameterized queries, you can mitigate the risk and ensure that user input is treated safely. Additionally, understanding detection techniques ...
Top answer
1 of 16
276

PreparedStatements are the way to go, because they make SQL injection impossible. Here's a simple example taking the user's input as the parameters:

public insertUser(String name, String email) {
   Connection conn = null;
   PreparedStatement stmt = null;
   try {
      conn = setupTheDatabaseConnectionSomehow();
      stmt = conn.prepareStatement("INSERT INTO person (name, email) values (?, ?)");
      stmt.setString(1, name);
      stmt.setString(2, email);
      stmt.executeUpdate();
   }
   finally {
      try {
         if (stmt != null) { stmt.close(); }
      }
      catch (Exception e) {
         // log this error
      }
      try {
         if (conn != null) { conn.close(); }
      }
      catch (Exception e) {
         // log this error
      }
   }
}

No matter what characters are in name and email, those characters will be placed directly in the database. They won't affect the INSERT statement in any way.

There are different set methods for different data types -- which one you use depends on what your database fields are. For example, if you have an INTEGER column in the database, you should use a setInt method. The PreparedStatement documentation lists all the different methods available for setting and getting data.

2 of 16
52

The only way to prevent SQL injection is with parameterized SQL. It simply isn't possible to build a filter that's smarter than the people who hack SQL for a living.

So use parameters for all input, updates, and where clauses. Dynamic SQL is simply an open door for hackers, and that includes dynamic SQL in stored procedures. Parameterize, parameterize, parameterize.

🌐
Acunetix
acunetix.com › how-to-prevent-sql-injections-java
How To Prevent SQL Injections in Java | Acunetix
March 5, 2025 - If possible, you should validate input against a whitelist and use parametrized queries also known as prepared statements in Java JDBC. To show you how to do this, we will use a simple example where the web application displays information on fish.
🌐
Okta Security
sec.okta.com › articles › 2020 › 12 › sql-injection-java-practices-avoid
SQL Injection in Java: Practices to Avoid | Okta Security
December 1, 2020 - We know that SQL injection vulnerabilities allow attackers to execute database queries, but how do they work? To answer this question, we're going to look at some vulnerable code to explain how the vulnerability works and how an attacker can take advantage of it. NOTE: In this example app we’ll look at the code using both JdbcTemplate and JPA. Let's start with some basic Java JDBC code.
🌐
Stack Overflow
stackoverflow.com › questions › 74345146 › how-to-detect-sql-injection-attempt
java - How to detect SQL injection attempt - Stack Overflow
Also, how would you distinguish genuine searches that just look like SQL injection, from actual SQL injection? You'd either create logs that no one will look at, or burn time "investigating" things, with no actual recourse (or even need) to address them. You waste time and money either way. ... you should employ web application firewall (waf) instead of baking some untested arcane code into your application logic directly.
🌐
Academia.edu
academia.edu › 13299455 › Methods_of_Detection_and_Prevention_of_SQL_Injection_with_Some_Java_Code
(PDF) Methods of Detection and Prevention of SQL Injection with Some Java Code
June 25, 2015 - Then we will detect the SQL injection and provide the detection algorithm includes these steps: lexicalanalysis of source code, parsing of source code, constructingabstract syntax tree of source code, defining rules of SQL injection attack.
🌐
AEANET
aeanet.org › home › how to prevent sql injection in java?
How to Prevent SQL Injection in Java? - AEANET
September 26, 2025 - This includes both code reviews and automated scanning tools. Frequency depends on the risk profile and change rate of your application, but quarterly or annual audits are common. There are various static and dynamic analysis tools available to help detect SQL Injection vulnerabilities.
🌐
Java Code Geeks
javacodegeeks.com › home › enterprise java
SQL Injection in Java Application
November 27, 2012 - And we will see how to solve and prevent the SQL Injection in java Web Application. For this purpose we need 1 tools. these tool are completely open source. SQL Map – SqlMap is an open source penetration testing tool that automates the process ...