Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape single quotes for SQL insert...when string to insert is in a user generated variable

Tags:

java

sql

jdbc

I am building an insert command to execute using jdbc. Part of it is to concatenate a user generated string...this all works until the user uses a string like this:

a'bcd

String userString="a'bcd"; String insertTableSQL = "INSERT INTO myTable "                             + "(insertColumn) "                              + "VALUES("                                 +"'"+userString+"'"                                 +")";  statement.executeUpdate(insertTableSQL); 
like image 280
user947659 Avatar asked Oct 13 '14 00:10

user947659


People also ask

How do I skip a single quote in SQL?

The simplest method to escape single quotes in SQL is to use two single quotes. For example, if you wanted to show the value O'Reilly, you would use two quotes in the middle instead of one. The single quote is the escape character in Oracle, SQL Server, MySQL, and PostgreSQL.

How do I use single quotes as part of a string in SQL?

If you need to use single quotes and double quotes in a string that contains both a contraction and a quote, you will need to use the backslash '' to cancel out the following character.

How do I escape a special character in SQL query?

Use braces to escape a string of characters or symbols. Everything within a set of braces in considered part of the escape sequence. When you use braces to escape a single character, the escaped character becomes a separate token in the query. Use the backslash character to escape a single character or symbol.


1 Answers

You can do either of the below:

  1. Use the PreparedStatement class. (Recommended)

    String userString="a'bcd"; String myStatement = " INSERT INTO MYTABLE (INSERTCOLUMN) VALUES (?)"; PreparedStatement statement= con.prepareStatement   (myStatement ); statement.setString(1,userString); statement.executeUpdate(); 
  2. Escape the single quotes.

    In SQL, single quotes will be escaped by using double single quotes. ' --> ''

    String userString="a'bcd"; String changedUserString = userString.replace("'","''");         //changedUserString  = a''bcd String insertTableSQL = "INSERT INTO myTable (insertColumn) VALUES("                         +" '"+changedUserString +"' )"; 
like image 79
Nishanthi Grashia Avatar answered Oct 08 '22 04:10

Nishanthi Grashia