1

I have asked this beacause i was not able to find the answer.

what i am doing is

 String selectTableSQL = "SELECT * FROM diseaseinfo WHERE diseaseName =""+diseaseName +'" AND name = '"+username+"'";

it is perfecty running unless and until diseases does not contain 's type of word like

Wilms' tumor

Addison's disease

etc....

so query like

SELECT * FROM diseaseinfo WHERE diseaseName = 'Adult Still's disease' AND name = 'add';

wont execute because of ' 's on 'Adult Still's

and also in java i cant start string with String selectTableSQL = ' '; it will always be in String selectTableSQL = " ";

any solution?

YCF_L
  • 51,266
  • 13
  • 85
  • 129
Aman
  • 778
  • 2
  • 11
  • 35
  • Use `PreparedStatement`(s) and ***bind* variables**. – Elliott Frisch May 12 '17 at 15:51
  • ok i will.Beside this any solution? @ElliottFrisch – Aman May 12 '17 at 15:53
  • Write a correct string escape utility? [`StringEscapeUtils.escapeSql(String)`](http://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeSql%28java.lang.String%29) (note that this is so non-trivial that the method has been removed from more recent versions of `StringEscapeUtils`). – Elliott Frisch May 12 '17 at 16:03
  • Hi @ElliottFrisch can you help me with this http://stackoverflow.com/questions/43957497/dynamic-column-name-using-preparestatement-sql-query-with-variable-containg-s – Aman May 13 '17 at 20:13

2 Answers2

0

The correct way to use queries in JDBC is to use PreparedStatement and bind variables.

But in your case, try replacing the single quotes ' in your values with \'.

You can use a simple diseaseName.replace("'", "\\'"); to do it.

Jerin Joseph
  • 1,078
  • 9
  • 17
0

To avoid this case and any syntax error or SQL Injection you have to use PreparedStatement instead :

String selectTableSQL = "SELECT * FROM diseaseinfo WHERE col1 = ? and col2 = ?";
try (PreparedStatement ps = connection.prepareStatement(selectTableSQL)) {

    ps.setString(1, value_1);
    ps.setString(2, value_2);
    ResultSet rs = ps.executeQuery();
    while(rs.next()){
        //...
    }
}
Graham
  • 7,035
  • 17
  • 57
  • 82
YCF_L
  • 51,266
  • 13
  • 85
  • 129