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:
You can do either of the below:
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();
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 +"' )";