javastring

Java replace ' " 'character with ' \" '


I am trying to update text into a MySql Database. The text contains " marks in it. As example string could be Hello "world" now when i write insert command its sumthing like

insert into mytable ('mystring') values("Hello "world"");

I am using java to execute a command like this. Obviously this gives an error due to the double quotes in the world string. I tried replacing it with java givenString.replaceAll("\"", "\\""); givenString.replace(Pattern.quote("\""), "\\"");

But nothing works . Any help is greatly appreciated !


Solution

  • Double escape the \ like so:

    givenString.replaceAll("\"", "\\\"");
    

    As stated by Ted Hopp in comments, for inserting data into a table you should user prepared statements using parameters, and set them according to the API you are using. For example if you are using JDBC you may use the setString method of your Statement object.

    String str = "Hello \"world";
    PreparedStatement stmt = con.prepareStatement(
          "insert into mytable('column') values(?)");
    stmt.setString(1, str);
    

    About your first comment:

    In Java Strings are immutable, so replaceAll returns a new instance whose contents is the string with the required replacements. So what you want is to assign again the result to the previous variable, like so:

    public String getSqlLikeString(String givenString) {
       System.out.println(givenString); 
       givenString = givenString.replaceAll("\"", "\\\""); 
       System.out.println(givenString); 
       return givenString;
    }
    
    // or just
    public String getSqlLikeString(String givenString) {
       return givenString.replaceAll("\"", "\\\"");
    }