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.

Answer from Kaleb Brasee on Stack Overflow
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.

🌐
Baeldung
baeldung.com › home › persistence › sql injection and how to prevent it?
SQL Injection and How to Prevent It? | Baeldung
March 18, 2026 - First, we use a whitelist to sanitize the column name, then we proceed to create a CriteriaQuery to fetch the records from the database. Let’s assume that we’ve used parameterized queries and/or whitelists everywhere.
🌐
arXiv
arxiv.org › pdf › 1009.3712 pdf
Preventing SQL Injection through Automatic Query ...
In this paper, we have presented the ASSIST technique for automatic query sanitization. ASSIST uses · a combination of static analysis and program transformation to automatically locate and perform sani- tization on host variables that are used to construct SQL queries. We have implemented our technique · in Java with a tool named ASSIST for protecting Java bytecode (derived from JSPs or Servlets). An · empirical evaluation demonstrated that ASSIST is effective against an SQL injection attack test suite and
🌐
SEI CERT
wiki.sei.cmu.edu › confluence › display › java › IDS00-J.+Prevent+SQL+injection
IDS00-J. Prevent SQL injection - SEI CERT Oracle Coding Standard for Java - Confluence
February 12, 2018 - The primary means of preventing SQL injection are sanitization and validation, which are typically implemented as parameterized queries and stored procedures. Suppose a system authenticates users by issuing the following query to a SQL database. If the query returns any results, authentication succeeds; otherwise, authentication fails. SELECT * FROM db_user WHERE username='<USERNAME>' AND password='<PASSWORD>' Suppose an attacker can substitute arbitrary strings for <USERNAME> and <PASSWORD>. In that case, the authentication mechanism can be bypassed by supplying the following <USERNAME> with an arbitrary password:
🌐
StackHawk
stackhawk.com › stackhawk, inc. › vulnerabilities and remediation › preventing sql injection in java
Java SQL Injection Guide: Examples and Prevention
January 10, 2025 - The best solution for the problem of SQL injections is parameterized queries. That means you don’t concatenate user-supplied values. Instead, you use placeholders for those values, ensuring the values themselves are never part of the text of the query. The parameters are then passed to the ...
🌐
DigitalOcean
digitalocean.com › community › tutorials › sql-injection-in-java
SQL Injection in Java and How to Easily Prevent it | DigitalOcean
August 3, 2022 - ‘1’=‘1’: It will be evaluated to true as this is static string comparison. Now combining all 3 conditions i.e false and false or true => Final result will be true. In the above scenario, we have used the boolean expression to perform SQL Injection. There are some other ways to do SQL Injection. In the next section, we will see ways to prevent SQL injection in our Java application.
🌐
Castsoftware
doc.castsoftware.com › export › AIPCONSOLE › User+Input+Security+-+Sanitization+and+co+-+how+to+protect+from+injection+flaws+and+how+to+define+them+in+AIP
User Input Security - Sanitization and co - how to protect from injection flaws and how to define them in AIP
February 20, 2024 - Define the variable binding (setString, setXYZ, setParameter, ...) as sanitization for SQL injection : stops the flow. In addition, "The JDBC driver will escape this data appropriately before the query is executed; making sure that data is used just as data" (See How to How to Fix SQL Injection ...
🌐
Sqreen
blog.sqreen.com › home › preventing sql injections in java (and other vulnerabilities)
Preventing SQL injections in Java (and other vulnerabilities) - Sqreen Blog
January 21, 2021 - The first and most important step you can take against SQL injection in Java is to use parameterized queries instead of concatenating values. What does that look like in practice? Here’s an example, based on the query we’ve shown in the previous section: String sql = "select id, title, excerpt, body from Posts where slug = ?";
Find elsewhere
🌐
SSOJet
ssojet.com › escaping › sql-escaping-in-java
SQL Escaping in Java | Escaping Techniques in Programming
The most effective defense against SQL injection in Java is using PreparedStatement. This class separates your SQL code from user-supplied data by employing placeholders (?). When you execute the query, the driver safely inserts the data into ...
Top answer
1 of 3
24

Right, prepared statement query parameters can be used only where you would use a single literal value. You can't use a parameter for a table name, a column name, a list of values, or any other SQL syntax.

So you have to interpolate your application variable into the SQL string and quote the string appropriately. Do use quoting to delimit your table name identifier, and escape the quote string by doubling it:

java.sql.DatabaseMetaData md = conn.getMetaData();
String q = md.getIdentifierQuoteString();
String sql = "SELECT MAX(AGE) FROM %s%s%s";
sql = String.format(sql, q, tablename.replaceAll(q, q+q), q);

For example, if your table name is literally table"name, and your RDBMS identifier quote character is ", then sql should contain a string like:

SELECT MAX(AGE) FROM "table""name"

I also agree with @ChssPly76's comment -- it's best if your user input is actually not the literal table name, but a signifier that your code maps into a table name, which you then interpolate into the SQL query. This gives you more assurance that no SQL injection can occur.

HashMap h = new HashMap<String,String>();
/* user-friendly table name maps to actual, ugly table name */
h.put("accounts", "tbl_accounts123");

userTablename = ... /* user input */
if (h.containsKey(userTablename)) {
  tablename = h.get(userTablename);
} else {
  throw ... /* Exception that user input is invalid */
}
String sql = "SELECT MAX(AGE) FROM %s";
/* we know the table names are safe because we wrote them */
sql = String.format(sql, tablename); 
2 of 3
3

Not possible. Best what you can do is to use String#format().

String sql = "SELECT MAX(AGE) FROM %s";
sql = String.format(sql, tablename);

Note that this doesn't avoid SQL injection risks. If the tablename is a user/client-controlled value, you'd need to sanitize it using String#replaceAll().

tablename = tablename.replaceAll("[^\\w]", "");

Hope this helps.

[Edit] I should add: do NOT use this for column values where you can use PreparedStatement for. Just continue using it the usual way for any column values.

[Edit2] Best would be to not let the user/client be able to enter the tablename the way it want, but better present a dropdown containing all valid tablenames (which you can obtain by DatabaseMetaData#getCatalogs()) in the UI so that the user/client can select it. Don't forget to check in the server side if the selection is valid because one could spoof the request parameters.

🌐
javathinking
javathinking.com › blog › java-escape-string-to-prevent-sql-injection
Prevent SQL Injection in Java: How to Escape Strings with replaceAll – Practical Examples
String unsafeInput = "O'Neil"; // Escape single quotes for PostgreSQL: Replace ' with '' String safeInput = unsafeInput.replaceAll("'", "''"); // Result: safeInput = "O''Neil" String sql = "INSERT INTO users (name) VALUES ('" + safeInput + "')"; // Final query: INSERT INTO users (name) VALUES ('O''Neil') replaceAll() only escapes characters you explicitly target. If you forget to escape ; or --, attackers can still inject:
🌐
LinkedIn
linkedin.com › all › engineering › web development
How can you prevent SQL injection in a Java web service?
September 20, 2023 - The backslash (\) is an escape character that prevents the single quote (') from terminating the string. Therefore, the query would not return any results, and the attacker would not be able to log in as admin. ... Integrate with ORM solutions instead executing raw SQL in Java code. This not only helps prevent SQL injections but also makes your code readable by abstracting lower level database operations, object oriented, and extensible to other types of databases I.e.
🌐
Bobby-tables
bobby-tables.com › java
Bobby Tables: A guide to preventing SQL injection > Java
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.bobbytables.mybatis.PeopleMapper"> <select id="selectPeopleByNameAndAge" resultType="list"> <!-- lastName and age are automatically sanitized ---> SELECT * FROM people WHERE lastName = #{lastName} AND age > #{age} </select> </mapper> public interface PeopleMapper { List<Person> selectPeopleByNameAndAge(@Param("lastName") String name, @Param("age") int age); } String name = //user input int age = //user input SqlSessionFactory
🌐
OWASP Cheat Sheet Series
cheatsheetseries.owasp.org › cheatsheets › SQL_Injection_Prevention_Cheat_Sheet.html
SQL Injection Prevention - OWASP Cheat Sheet Series
Also, prepared statements ensure that an attacker cannot change the intent of a query, even if SQL commands are inserted by an attacker. In the safe Java example below, if an attacker were to enter the userID as tom' or '1'='1, the parameterized query would look for a username that literally matches the entire string tom' or '1'='1. Thus, the database would be protected against injections of malicious SQL code.
🌐
Acunetix
acunetix.com › how-to-prevent-sql-injections-java
How To Prevent SQL Injections in Java | Acunetix
March 5, 2025 - To prevent SQL Injection attacks in Java, you must treat user input passed to the SQL queries as untrusted and avoid dynamic SQL queries created using simple string concatenation.
🌐
Wyzant
wyzant.com › resources › ask an expert
Java - escape string to prevent SQL injection? | Wyzant Ask An Expert
April 5, 2019 - //write the statement, "?" in this case is the spot for whatever data you want
🌐
Coderanch
coderanch.com › t › 750740 › engineering › easy-sanitize-input-data-prevent
Is there an easy way to sanitize input data to prevent injection of code? (Security forum at Coderanch)
April 5, 2022 - Sanitize the input just before it is being used in a certain way. There's no single magic bullet that will work for every purpose. Want to store your input in a database? Use a prepared statement. Want to display user input on a web page? Use a page template and tell the template engine that you're about to inject unsanitized input. There's one very obvious red flag: If you ever use string operations on user input, such as string concatenation, then you're probably setting yourself up for disaster.