Java - escape string to prevent SQL injection Java - escape string to prevent SQL injection java java

Java - escape string to prevent SQL injection


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.


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.


If really you can't use Defense Option 1: Prepared Statements (Parameterized Queries) or Defense Option 2: Stored Procedures, don't build your own tool, use the OWASP Enterprise Security API. From the OWASP ESAPI hosted on Google Code:

Don’t write your own security controls! Reinventing the wheel when it comes to developing security controls for every web application or web service leads to wasted time and massive security holes. The OWASP Enterprise Security API (ESAPI) Toolkits help software developers guard against security‐related design and implementation flaws.

For more details, see Preventing SQL Injection in Java and SQL Injection Prevention Cheat Sheet.

Pay a special attention to Defense Option 3: Escaping All User Supplied Input that introduces the OWASP ESAPI project).