Escaping characters in string for MySQL

           String explain = "this piece of text includes single quotes ' and plus signs + and other chars that MySQL doesn't like";
            Statement state_commit = DBCon.con.createStatement();
            String sqlString = "UPDATE velocity SET speedExplain = '" + explain + "' WHERE shipName = 'pelican';";
            state_commit.execute(sqlString);
            Is there a java class which will prepare the string so that MySQL has no problem with it? I have tried in vain to get one such one : EscapeProcesor to work.
Much obliged for any help

DrLaszloJamf wrote:
Always, ALWAYS, use PreparedStatement:
http://java.sun.com/docs/books/tutorial/jdbc/basics/prepared.html
Or don't:
http://www.theregister.co.uk/2008/01/21/riaa_hacktivism/

Similar Messages

  • Need JDBC driver string for MYSQL DB Resin server

    Please any body provide me the jdbc driver for MYSQL
    database for Resin server
    Thanks

    The driver and URL string are independent of server you deploy them on.
    Put that JDBC JAR in your Web app's WEB-INF/lib directory and it'll be in the CLASSPATH.
    Set up the pooled data source as appropriate for your server. That's the server-dependent part.
    %

  • Format large string for mysql

    I am reading a large txt file that contains sigle quotes and double quotes... I want to format the string and send it to a blob cell in mysql. I need to add an escaoe character before single quotes and double quotes. Any suggestions?

    john joe wrote:
    I am reading a large txt file that contains sigle quotes and double quotes... I want to format the string and send it to a blob cell in mysql. I need to add an escaoe character before single quotes and double quotes. Any suggestions?
    Yes!  Use "Search and Replace String" with "replace all?" = True.  Replace "'" with "\'" and replace """ with "\"".
    Cheers.
    Message Edited by tbd on 02-12-2007 11:06 PM
    "Inside every large program is a small program struggling to get out." (attributed to Tony Hoare)

  • Report Designer odbc connection string for data source using a parameter

    I am using stand alone report designer 3 for the present and have a question/problem regarding the odbc connection string for MySQL when setting up the data-source
    I need to be able to enter a parameter which is the database name i.e. BOE-201401 or say BOE-201312 etc  from a list of databases the user can choose from.
    at present the odbc connection string points to BOE-201402
    the connection string is at present  Dsn=Development Server for MYsql;description=MYSQL;server=ldndw01;database=BOE-201402;port=3306
    my parameter has the name BOE_DATABASE
    and in an expression it is  as such
    =Parameters!BOE_DATABASE.Value
    I want to point the datasource for the report to the parameter value before the user sees the report.

    Hi Leslie,
    Based on your description, we want to design a report with a dynamic DataSource connection string. There are the basic steps below for your reference:
    Create report with static database.
    Change data source to report parameter.
    Send new database connection string as a report parameter. 
    More detail information, please refer to the following blog: Dynamic Database in SSRS 2008.
    http://haseebmukhtar.wordpress.com/2011/11/09/dynamic-database-in-ssrs-2008/
    Regards,
    Alisa Tang
    Alisa Tang
    TechNet Community Support

  • Problem with JDBC driver for mysql

    I have downloaded the Connector/J3.0 mysql-connector-java-3.0.7-stable.tar.gz from www.mysql.com/downloads/api-jdbc-stable.html web site and used gunzip and tar to extract the file. I have received the following error message:
    tar: directory checksum error
    Will this error cause some problem later on?
    Which directory should I put the driver into? Can I put it in any directory?
    Do I need to set the classpath for the driver? If yes, how can I set it?
    What is the connect string? Can you give a sample for me? I am using Solaris 5.8 and mysql is on the same machine.
    Thanks a lot,
    Lisa

    this is an example of a connect string for mysql that i used...
    public Connection CreateConnection () throws Exception
         Connection myConn = null;
         String driverName = "org.gjt.mm.mysql.Driver";
         String dbUrl = "jdbc:mysql://www.desres.com/jhazrd?user=jhazrd&password=????";
         Class.forName(driverName);
         myConn = DriverManager.getConnection (dbUrl);
    return myConn;
    }

  • Setting escape characters for a MySQL insertion

    Hello all. I'm trying to format an incoming string with escaped characters so I can insert them into a mysql database... a quick rundown would be
    ' replaced with \'
    " replaced with \"
    escaping newline characters with the literal text "\n" (without quotes)
    escaping arriage return characters with the literal text "\r" (without quotes)
    for some reason it's not working out. Here's the method I made to handle it:
      public static String mysqlEncode(String stringToEncode) {
        String returnString = stringToEncode;
        // Replace " with \"
        if (returnString.matches("\\\"")) returnString = returnString.replaceAll("\\\"", "\\\"");
        // Replace ' with \'
        if (returnString.matches("'")) returnString = returnString.replaceAll("'", "\\'");
        // Replace \ with \\
        if (returnString.matches("\\\\")) returnString = returnString.replaceAll("\\\\", "\\\\");
        // Replace newlines with \n
        if (returnString.matches("\\n")) returnString = returnString.replaceAll("\\n", "\\n");
        // Replace carriage returns with \r
        if (returnString.matches("\\r")) returnString = returnString.replaceAll("\\r", "\\r");
        return returnString;
      }and it keeps bombing out , I'm on my 3rd hour at this and it's really starting to irk me...
    questions:
    are my regular expressions formed correctly?
    is that if statement calling the .matches() method necessary?
    Thanks so much for your help.

    String sql = "SELECT * FROM MyTable WHERE author = ? AND text = ?";
    PreparedStatement pstm = connection.prepareStatement(sql);
    synchronized(pstm){  // if you're doing multithreading stuff (if single thread..you can ignore the synchronized
        pstm.clearParameters();
        pstm.setString(1, "Anne Rice");    //  1 = the first question mark in the String sql
        pstm.setString(2, "The Vampire Lestat's long fangs");
    ResultSet res = pstm.executeQuery();
    while (res.next()){
    }same thing for INSERT, UPDATE, etc..

  • Escaping a string for Javascript

    Hi!
    I've been using a lot of time on how to escape special characters in order for Javascript to accept a string. It seems like I need to escape single quotes, double quotes, backslash and newline.
    I've written some code, but I just can't get it to work.
    public static String editorSafeFilter(String text)
            if(text == null){
                return null;
            StringBuffer buffer = new StringBuffer(text.length());
             for (int i = 0; i < text.length(); i++) {
                char ch = text.charAt(i);
                 switch (ch) {
                   case 10: // '\n'
                        buffer.append(" ");
                        break;
                    case 13:
                         buffer.append(" ");     // '\r'
                         break;
                    case '\'':
                        buffer.append('\\');
                        buffer.append("\'");
                        break;
                    case '"':
                        buffer.append('\\');
                        buffer.append('\"');
                        break;
                    case '\\':
                        buffer.append('\\');
                        buffer.append('\\');
                        break;
                    default :
                        buffer.append(ch);
                        break;
            return buffer.toString();
        }Anyone have any links or sample code that works?
    thanks!
    Vidar

    It looks like you want the actual escape sequences... public static String editorSafeFilter(String text)
            if(text == null){
                return null;
            StringBuffer buffer = new StringBuffer(text.length());
             for (int i = 0; i < text.length(); i++) {
                char ch = text.charAt(i);
                 switch (ch) {
                   case '\012': // '\n'
                        buffer.append("\\n");     // '\n'
                        break;
                    case '\015':
                        buffer.append("\\r");     // '\r'
                        break;
                    case '\'':
                        buffer.append("\\\'");
                        break;
                    case '\"':
                        buffer.append("\\\"");
                        break;
                    case '\\':
                        buffer.append("\\\\");
                        break;
                    default :
                        buffer.append(ch);
                        break;
            return buffer.toString();
        }

  • Stop escaped characters from resolving within String class.

    Hello,
    Is it possible to stop escaped characters from resolving within the String class?
    For example, I define a character array,
    char[] c = {'0','\\','n'}
    and I want to create a String based on this exact sequence (0\n). However, when I call the String constructor String(char[]), it resolves the \n sequence into the newline character, creating a String of length 2 not 3.
    I'm not very familiar with the innards of the Java compiler (does "xyz" translate to char[]{'x','y','z'}?), so maybe this is something very basic.
    Does anyone know if there is a flag that can be set somehow before I create a String instance (it appears that no String constructor supports this kind flag)?
    Or perhaps is there a method in the standard Java release that escapes all escape characters in a character array...? I'm curious if there is a simpler way (like a flag), because the method approach seems superfluous.
    Thanks,
    Brien

    What do you mean?char[] c = {'0', '\\', 'n'};
    String s = new String(c);
    System.out.println(s);does give the string 0\n...
    And by the way, it's not the String class that transforms \n to the linefeed character, it is the compiler..

  • How to replace escape characters in a string ?

    Hi All,
    In my application I came across a problem where I want to replace a substring (contains escape characters also) with another string. The below shown code will replicate my problem :
    public class StringSearchAndReplace {
      public static void main(String args[])   {
        String stmt = " \\pntext\\bullet\\tab The question as to ";
        String newStmt = stmt.replaceAll("\\bullet\\tab",  "B");
        System.out.println("BEFORE: " + stmt + "\n");
        System.out.println("AFTER: " + newStmt);
    }Here I want to replace "\\bullet\\tab" with "B". I am unable to move further. Please help/suggest me in this regard.
    Its urgent.
    Thanks in advance.

    Satyaprasad_Mylavarapu wrote:
    Hi All,
    In my application I came across a problem where I want to replace a substring (contains escape characters also) with another string. The below shown code will replicate my problem :
    public class StringSearchAndReplace {
    public static void main(String args[])   {
    String stmt = " \\pntext\\bullet\\tab The question as to ";
    String newStmt = stmt.replaceAll("\\bullet\\tab",  "B");
    System.out.println("BEFORE: " + stmt + "\n");
    System.out.println("AFTER: " + newStmt);
    }Here I want to replace "\\bullet\\tab" with "B". I am unable to move further. Please help/suggest me in this regard.
    Its urgent.
    Thanks in advance.If the String you're trying to replace contains a slash you need four slashes (double it for java, then again because String.replaceAll takes a regular expression)
    So I think what you're looking for is:
    String newStmt = stmt.replaceAll("\\\\bullet\\\\tab",  "B");I haven't tested that though.

  • Escape characters for SQL

    Help me out here! i'm having a problem updating our database with this call:
    update table
    set name = 'dave's store'
    where id = '2';
    The problem of course is that single quote in the name. i've check many sites and have tired everything.
    -i have tried to escape the quote with a back (and forward!) slash, and nothing.
    -i have padded the quote with another single quite (ie ''), but that doesn't work.
    -i have have nearly all combinations of single and double quotes, with and without escape characters!
    according to the documention, just the blackslash so be fine! any one have this problem as well?
    any help would be greatly appreciated! thanks.

    Very related question.
    Is there a way to make sure that all 'weird' characters in an SQL statement are escaped properly before the statement is executed?
    I'm hoping that there is a method like this:
    Statement stmt = stmt.escapeAllBadChars();
    Is there such a method anywhere?
    I can't find it anywhere :(
    If not, is there a list of all 'bad characters' anywhere?
    Thanks,
    Otis
    null

  • Issue with escaping characters and php

    Greetings,
    We are working on a web page using php and Oracle. We have troubles dealing with the diferent escaping characters when inserting/retrieving data (magic quotes is on but adding the backslash doesn't help :( ).
    We would like to know the correct way of dealing with those characters ( ' " / /n ...).
    Thank you in advance,
    Sincerely,
    Oriol Nonell

    Do NOT use addslashes/stripslashes to escape your queries. I use this function to do the escaping:
    function escapeSQL($string, $wildcard=false)
    $result = str_replace("'","''",$string);
    if ($wildcard == true) $result = str_replace("%","%%",$result);
    return $result;
    It basically replaces ' with ''.
    If you set $wildcard to false, then '%' is considered to be an actual '%' (for 'like' expressions). If you set it to true, a % is escaped to %% too.

  • Displaying unicode or HTML escaped characters from HTTPService in Flex components.

    Here is a solution on the Flex Cookbook I developed for
    displaying data in Flex components when the data comes back from
    HTTPService as unicode of HTML escaped data:
    Displaying
    unicode or HTML escaped characters from HTTPService in Flex
    components.

    Hi again Greg,
    I have just been adapting your idea for encountering
    occasional escaped characters within a body of "normal" text, eg
    something like
    hell&ocirc; sun&scaron;ine
    Now, the handy String.fromCharCode(charCode) call works a
    dream if instead of the above I have
    hell&#244; sun&#353;ine
    Do you know if there is an equivalent call that takes the
    named entities rather than the numeric ones? Clearly I can just do
    some text substitution to get the mapping, but this means rather
    more by-hand work than I had hoped. However, this is definitely a
    step in a useful direction for me.
    Thanks,
    Richard
    PS hoping that the web page won't simply outguess me and
    replace all the above! Basically, the first line uses named
    entities and the second the equivalent numbers...

  • Bug in replace all. escape characters are not working.

    Hi,
    My requirement is that whenever i see ":" (Colon) in the string then i want to replace it with (\:). So i tried
    String escapedTitle = "title:the world is not enough".replace(":", "\\:")
    and to my surprise, when i printed escapedTitle i got
    title\\:the world is not enough
    instead of
    title\:the world is not enough
    (note the back slash in the string)
    I want to ask why there is a different beehavious of escape characters? I am using JDK1.6.0_06

    Sorry for the last post. Please try this:
    public class test
    public static void main(String a[])
         String escapedTitle = "title:the world is not enough".replaceAll(":+", "\\:"); //or [:]+
         String escapedTitle1 = "title:the world is not enough".replaceAll(":+", "*"); // or [:]+
         System.out.println("Another String is "+ escapedTitle);
         System.out.println("Another String is "+ escapedTitle1);
         System.out.println(System.getProperty("java.vendor"));
         System.out.println(System.getProperty("java.version"));
    output is
    Another String is title:the world is not enough
    Another String is titlethe* world is not enough
    Sun Microsystems Inc.
    1.6.0_06
    Please let me know why i am not getting : as escaped (\:) with replaceAll method.
    i want string escapedTitle as Another String is title*\:*the world is not enough

  • Dealing with escape characters

    I have a command that works if I represent it as "\003"+command+"\r" because my command needs to be preceded by the char 'x03' and tailed by the char 'x0d'. The literals "\003" and "\r" are being converted as I wish into their equivalent byte values.
    If I use Java string variables 'start' and 'end' to hold the values "\003" and "\r" and I issue my command as 'start+command+end', the start and end values are NOT converted into byte values. They remain represented as they are written i.e my string command is preceded by '\003' and ends with '\r'.
    How can I convert escape characters stored in string variable into their byte equivalents?
    David

    Please show us the code, because what you say isn't clear. If the Strings are written as
    String start = "\003";  // etx
    String end = "\r";   //crIt should work.
    Often this sort of thing is easier to do with character variable. eg.
    char start = 3;  // etx
    char end = 13;  // crI also wonder why you are using etx (end of text) as the start of text, the usual choice would be stx=\002. Also, none of this has anything to do with "byte" values, they are characters and take 2 bytes each. Your network code can do that conversion for you after you choose your character set. Is it UTF8, Latin-1, or some other.

  • Evaluation of escape characters

    I'm convinced there has got to be an easy way to do this, but I am too frustrated at this point to continue fighting it... I would much appreciate anyone's help.
    Let me use code to explain what I need help with.
    I have a String that contains the right hand side of a java String assignment. To simulate this:
    String rightHandSide = "\"line1\\nline2\\nline3\""so a println of rightHandSide LITERALLY displays:
    "line1\nline2\nline3"
    (notice the quotes and "escape characters" are are actually literal characters).
    I want to be able assign the evaluation/interpretation of this String to a String variable, such that:
    String escValue = workMagic(rightHandSide)is equivalent to:
    String escValue = "line1\nline2\nline3"Can anyone offer a simple solution to this problem? If the only solution involves writing my own parser, etc, I will just give up for now and work around this issue. However, it seems like there should be an easy way to do this?
    Thanks in advance for any and all help!

    Not too sure if this is what you wanted:
    workMagic.java
    ============
    public class workMagic {
       public static void main(String[] args) {
          String rightHandSide = "\"line1\\nline2\\nline3\"";
          String escValue = workMagic(rightHandSide);
          System.out.println(escValue);
       public static String workMagic(String in) {
          String out="";
          int k;
          int j=0;
          while (j<in.length()) {
             if (in.charAt(j)=='\\') {
                j++;
                if (j<in.length()) {
                   if (in.charAt(j)!='\\') out+="\\"+in.charAt(j);
                   else j--;
                } else out+='\\';
             } else if (in.charAt(j)!='\"') out+=in.charAt(j);
             j++;
          return out;
    }V.V.

Maybe you are looking for

  • Creative mp3 and audiobo

    It seems a bit silly to post a request for sales help to the forum, but the responses I get from Creative are nonsensical and never actually answer my questions, so here goes. I have a Zen V. After the firmware update that allowed transfer of large f

  • Regarding Text in Credit note

    Dear All, I have taken 5 Materials from Customers ( Returns ) and raised Retruns sales order / Delivery and Credit Memo. In my credit note i have to get the text as " Credit note towards customer returns order number XXXXXXX " i.e. on the print of th

  • When I try to send an email I get the message rejected by the server because it does not allow relaying.  I have sent mails for months with no problems. Can anyone help

    When I try to send an email I get the message rejected by the server because it does not allow relaying.  I have sent mails for months with no problems but has started to be recoccuring. Can anyone help please as its pointless having email on my phon

  • I can't get into Muse.

    I get charged monthly to my card, yet none of my Adobe ID's say I own it. I already used my trial, and then payed for it. And now whenever I go into the application, it says I need to buy it, but I am already paying for it. What should I do?

  • Mark a report as saved thru code in an add-in.

    Is there a way to 'mark' a report within Crystal Report as saved? So if you close Crystal Reports the question 'Would you like to save the changes?' is suppressed as if the report is saved already. I want to do this 'to a report' from within an Add-I