A logo showing the text blog.marcnuri.com
Español
Home»Java»Replacing Apostrophes from Strings // Cleaning String to pass them as SQL statements

Recent Posts

  • Fabric8 Kubernetes Client 7.2 is now available!
  • Connecting to an MCP Server from JavaScript using AI SDK
  • Connecting to an MCP Server from JavaScript using LangChain.js
  • The Future of Developer Tools: Adapting to Machine-Based Developers
  • Connecting to a Model Context Protocol (MCP) Server from Java using LangChain4j

Categories

  • Artificial Intelligence
  • Front-end
  • Go
  • Industry and business
  • Java
  • JavaScript
  • Legacy
  • Operations
  • Personal
  • Pet projects
  • Tools

Archives

  • May 2025
  • April 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024
  • November 2024
  • August 2024
  • June 2024
  • May 2024
  • April 2024
  • March 2024
  • February 2024
  • January 2024
  • December 2023
  • November 2023
  • October 2023
  • September 2023
  • August 2023
  • July 2023
  • June 2023
  • May 2023
  • April 2023
  • March 2023
  • February 2023
  • January 2023
  • December 2022
  • November 2022
  • October 2022
  • September 2022
  • August 2022
  • July 2022
  • June 2022
  • May 2022
  • March 2022
  • February 2022
  • January 2022
  • December 2021
  • November 2021
  • October 2021
  • September 2021
  • August 2021
  • July 2021
  • January 2021
  • December 2020
  • November 2020
  • October 2020
  • September 2020
  • August 2020
  • July 2020
  • June 2020
  • May 2020
  • February 2020
  • January 2020
  • December 2019
  • October 2019
  • September 2019
  • July 2019
  • March 2019
  • November 2018
  • July 2018
  • June 2018
  • May 2018
  • April 2018
  • March 2018
  • February 2018
  • December 2017
  • July 2017
  • January 2017
  • December 2015
  • November 2015
  • December 2014
  • March 2014
  • February 2011
  • November 2008
  • June 2008
  • May 2008
  • April 2008
  • January 2008
  • November 2007
  • September 2007
  • August 2007
  • July 2007
  • June 2007
  • May 2007
  • April 2007
  • March 2007

Replacing Apostrophes from Strings // Cleaning String to pass them as SQL statements

2007-06-07 in Java / Legacy tagged Database / Java / Replace / String by Marc Nuri | Last updated: 2021-08-28

IMPORTANT NOTICE
This post was published in 2007 and some code was used to interact with databases that had no JDBC connector neither a prepared statement alternative.
It is a very bad practice and unrecommended to send SQL statements directly to a database.

Such a simple thing as replacing an apostrophe with an escape character from a string sometimes can become a very tedious process, more if you're using String's replaceAll(...) function.Replacing apostrophes from Strings may be very useful when creating Statements to pass to an SQL database, to prevent SQL injection. Using PreparedStatements is easier and safer, but on many occasions, you can't use prepared statements to accomplish what you need.

The problem with the replaceAll function comes because of the arguments the function expects and which might be unclear for newbie developers. In the first place, you must pass a regular expression that suits what you want to replace. Secondly, the function expects another regular expression with the String's replacement. In some systems when passing apostrophes and other special characters as text, you must use the backslash as an escape character, just like in java. So if you want to insert "John's hand" as an argument to an Insert statement you must write something such as 'John\'s hand'.

If you refer to Pattern JavaDoc you can read:

The backslash character ('\') serves to introduce escaped constructs, as defined in the table above, as well as to quote characters that otherwise would be interpreted as unescaped constructs. Thus the expression \\ matches a single backslash and \{ matches a left brace.

Here is the answer to the problem. When replacing ' for \' you need to place 4 backslashes before the apostrophe.

1String replacedString = "John's hand";
2replacedString.replaceAll("'","\\\\'");
Twitter iconFacebook iconLinkedIn iconPinterest iconEmail icon

Comments in "Replacing Apostrophes from Strings // Cleaning String to pass them as SQL statements"

  • Avatar for Richard Rodger
    Richard Rodger
    2007-06-07 11:49
    Yeah - it sure would be nice to have literal regexs in Java - would solve all that sort of stuff.

    For the specific case you mention, I think you would be better off using the '?' argument notation provided by JDBC PreparedStatements, rather than rolling your own. The Postgres driver should take care of it for you.
  • Avatar for Marc Nuri
    Marc Nuri
    2007-06-07 13:12
    You're totally right, prepared statements solve this issue in a very easy way. But sometimes you don't want to use PreparedStatements in terms of performance. If the statement is run only once during all the app's lifecycle statements have better performance than prepared statments.

    http://www.onjava.com/pub/a/onjava/excerpt/oraclejdbc_19/index.html?page=1
  • Avatar for Master of Nothing
    Master of Nothing
    2007-06-07 12:44
    I guess it would be a pain in the ass to escape all your String parameters to an SQL statement. Luckily for me I have never come across a instance where I had to pick Statements over PreparedStatements. Actually I haven't worked at the JDBC API level in the last 3 years , thanks to EJB, Hibernate and iBatis :)
  • Avatar for Marc Nuri
    Marc Nuri
    2007-06-07 15:03
    It certainly is.

    You can always add a utils function to avoid some boilerplate:
    public static String parseSQL(String in) {
      return in.replaceAll("'", "\\\\").replaceAll(/* ...other replacements...*/);
    }
    This way, you can call this function any time you need to pass an argument to an SQL statement.
  • Avatar for Brunis
    Brunis
    2008-04-05 13:57
    as was mentioned on Sun's Java forums, the two ticks is the ANSI standard, so replacing a ' with '' would be easier.. but PS is surely the way to go for oft repeated statements.
  • Avatar for Tessa
    Tessa
    2013-01-06 14:37
    Although your conclusion reridgang the regex pattern is correct, the function you suggest as a bad example is actually worse than just bad practice. It simply won't work.if StringUtils.hasLength sText sText= sText.replaceAll " ", " AND " ; sText= sText.replaceAll " ", " AND " ; sText= sText.replaceAll " ", " AND " ; sText= sText.replaceAll " ", " AND " ; sText= sText.replaceAll " ", " AND " ; The first replaceAll used on"Hello Google"will result in"Hello AND AND AND AND AND AND AND AND AND AND AND AND Google"and the subsequent replaceAlls will never be matching anything.

Post navigation
Getting started with JasperReports // Reporting in Java (Part I)Detecting Tab Key Pressed Event in JTextField's // Event.VK_TAB KeyPressed
© 2007 - 2025 Marc Nuri