Escaping single quotes in SQL Statement

I am getting SQL Statement error when i tried to have a value with a single quote in it ,inside my SQL Statement.
e.g.
INSERT INTO tblHoldings(Title) VALUES ('Developing Asia�s fibre processing through collaboration');
here the Title to be inserted in the table tblHoldings is "Developing Asia�s fibre processing through collaboration"
i used to trapped the single quote by using its escape character ( \ ) with this method and its fine with MySQL 4 but when I upgraded to MySQL 5.0.22, I now getting the SQL Statement error again.
public String cleanse(String dirty) {
      String clean = dirty.replaceAll("\'", "\\\\'");         
      return clean;
  }    please help me..how can i trapped/escape single quote in MySQL 5 in Java?
Thanks in advance for your help.

No. Please use PreparedStatements. That is theonly
correct answer to this question.Ok please tell us. how would you use prepare
statement.. no just say USE PREPARE STATE.. givethe
guy the code... or help..What size spoon would you like to be fed with? There
was nothing about gob size in the original post.
http://www.javaalmanac.com
well duffymo.. i think you gave a link, is quite of help, but my friend preparestatement just gave "use preparestatement"..
i think even you when you start coding you needed help... and some one just tell you use preparestatement how do you feel..
There is a level of help. i think it will be (((as much as you can)))

Similar Messages

  • How do I escape single quotes in SQL queries

    Hi
    I am using EclipseLink + EJB 3.0.
    When single quote ( ' ) is entered as search criteria for JPA query, it throws exception.
    As specified in the bolow link , its generic sql problem.
    http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F
    If single-quote is used to escape a single-quote, it might fail in mySQL (which use a backslash as the escape character).
    Please suggest generic way to resolve this issue, so that it works across DBMS.
    Thanks
    Tilak

    Hello,
    I'm not sure of the query you are trying to execute, or why you would link an article that is strongly suggestiong parameter binding when you state you are looking for escape characters. If you pass in the parameter, you do not need to use escape characters, and EclipseLink uses parameter binding by default.
    What is the exception you are getting, and the SQL that is generated? Is this a native query or a JPQL query?
    Best Regards,
    Chris

  • Embedded Single Quote in SQL Column truncates Java String

    I have a jsp web page that queries a database to see what day a user is registered for and then produces an URL for the user to click on. My problem is that the URL being processed stops when an embedded single quote is encountered.
    Here is the database side:
    Database side:
    Create Table registration
    (reg_id int not null,
    name varchar2(45) not null,
    day_nb int not null);
    Insert into registration
    (reg_id, name, day_nb)
    values (1043,'Johnny''s Diner', 1);
    Select name, day_nb from registration
    where reg_id = 1043;
    name, day_nb
    Johnny's Diner 1
    Snippet of relevant java code: (JSP page)
    <%
    int day_nb = rs.getInt("day_nb");
    String particpant_name = rs.getString("name");
    System.out.println("registration.jsp: particpant_name = " + particpant_name);
    %>
    <td width="84%">
         <a
         href='<%=response.encodeURL("registrationHandler.jsp?"particpant_name="+ particpant_name + "&day_nb="+ day_nb)%>'><%=particpant_name%>
                                  </a>
                             </td>
    {code}
    The following is printed to System.Out:
    registration.jsp: particpant_name = Johnny's Diner
    The code produces the following URL
    http://www.mycompany.com/registrationHandler.jsp?particpant_name=Johnny
    The response.encodeURL is stopping on the single quote contained in "Johnny's Diner"
    The URL I want is:
    http://www.mycompany.com/registrationHandler.jsp?particpant_name=Johnny's Diner&day_nb=1
    How do I account for the embedded single quote so the code works properly? Thanks In Advance!                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    You really need to read up on [SQL Injection|http://en.wikipedia.org/wiki/SQL_injection] and [XSS/Cross-Site Scripting|http://de.wikipedia.org/wiki/Cross-Site_Scripting]. Both present massive security problems and your code seems prone to easily producing both.
    For SQL Injection attacks the correct solution is to always use PreparedStatements with only hard-coded String (i.e. never use String concatenation to build SQL statements).
    For XSS attacks the solution is a bit harder, but basically you need to learn never to trust user input (that includes user input that you've previously stored in the database!) and always escape what the user sent when you print it back out.

  • Escaping single quotes

    I didn't write the original database access/pooling code for this web app, and right now we've got an issue with single quotes in data not being escaped properly. I've read that PreparedStatement takes care of this for you, but I've only started using it for a few CLOB/BLOB inserts, etc, since we started converting to Oracle. Right now, the majority of our updates run through the following method, and this method gets called 45 times in our code:
    public boolean runQuery(String query) {
       boolean runsuccess = false;
       PooledConnection Con = null;
       Statement Stmt = null;
       try {
         Con = oPool.getConnection();
         Stmt = Con.createStatement();
         Stmt.execute(query);
         runsuccess = true;
         Stmt.close();
       } catch(SQLException sqlerr) {
         if(Stmt != null) {
           try {
             Stmt.close();
           catch(SQLException err) {}
         System.out.println("SQL Error in DBACCESS 1: " + sqlerr + " Running Query: " + query);
         runsuccess = false;
       finally {
         if(Con != null) {
           oPool.returnConnection(Con);
       return runsuccess;
    }It seems like a quick and dirty but decent short-term solution could be to just change this to use a PreparedStatement (without any parameters). I don't have much time at the moment, and we just need something that will work without introducing other issues. While I'm at it, should I also change the following method that is used for the majority of our reads (SELECTs) out of the database?
    public synchronized ResultSet loadValues(String query) {
       try {
         loadCon = oPool.getConnection();
         loadStmt = loadCon.createStatement();
         RS = loadStmt.executeQuery(query);
       catch(SQLException sqlerr) {
         closeCon();
         System.out.println("Error Running SQL: " + sqlerr + " Running Query: " + query);
         sErrTxt = sqlerr.toString();
       return RS;
    }Thanks for the advice...

    Stephen,
    As you were told in the reply you got to this same question that you posted to the JavaRanch forum (<- that's a link: click on it to go to your "JavaRanch" posting), merely replacing "Statement" with "PreparedStatement" will not help.
    From the code you have posted, it looks like the "runQuery()" method is for performing DML (deletes, inserts and updates), while the "loadValues()" method is for fetching data from the database.
    I believe the best solution will be to take the time to refactor your code. While I don't know any details of your situation (because you didn't provide any :-), taking the time to refactor the code properly will usually save you lots more time in the future.
    For what it's worth, our generic version of your "runQuery()" method is this:
    public int executeUpdate(String sql, Object[] params, int[] types)where "sql" contains "?" (question-mark) characters, "params" holds the values for the "?" parameters, and "types" holds the (SQL) data types for the "?" parameters (in case you want to assign null to any of the "?" parameters). The method creates a "PreparedStatement" and uses the "setXXX()" methods (in "PreparedStatement") -- as well as the "setNull()" method (if necessary) -- to assign values to the "?" parameters. It returns the value returned from "PreparedStatement.executeUpdate()" -- the number of rows affected.
    Similarly, our equivalent to your "loadValues()" method is:
    public ResultSet executeQuery(String sql, Object[] params, int[] types)This means changing the API, which means changing all the code that invokes these methods, but again, I would suggest that the time spent doing this now will save you lots of time in the long run.
    Good Luck,
    Avi.

  • Escaping Single Quotes in UIX LOVs

    Hello all,
    I am creating an application using ADF and UIX. In the system, I am using the standard UIX LOV, and I am curious if there is an existing way of handling single quotes entered by users in the search area. By default (at least in my case), single quotes cause an error in the SQL query, so I would like to escape them before the query is run. I attempted to override the onLovFilter method to handle this, but it seems like the LOV window does not actually fire any events or call overridden methods. I also overrode prepareMode to simply output "hello" when it is called, to test if any events were really being fired, but my method looks like it is simply being ignored. Is there a simpler way to avoid troubles caused by single quotes? Or can anyone help me override methods in LOVs? Thanks in advance.
    Regards,
    John

    No. Please use PreparedStatements. That is theonly
    correct answer to this question.Ok please tell us. how would you use prepare
    statement.. no just say USE PREPARE STATE.. givethe
    guy the code... or help..What size spoon would you like to be fed with? There
    was nothing about gob size in the original post.
    http://www.javaalmanac.com
    well duffymo.. i think you gave a link, is quite of help, but my friend preparestatement just gave "use preparestatement"..
    i think even you when you start coding you needed help... and some one just tell you use preparestatement how do you feel..
    There is a level of help. i think it will be (((as much as you can)))

  • Escape single quote from a String variable

    Hi,
    I have a String variable called "name" which i am using in my form tag.
    <form name=test action="test.jsp?fname=<%=name%>" method="post">
    But i am getting Javascript error if the "name" variable contains a string with some special characters like single quote( ' ).
    Plz help me to escape this special char from my String variable.
    Thanks..

    You need to url-encode the value using the URLEncoder class.
    http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html
    For example:
    <form name=test action="test.jsp?fname=<%=URLEncoder.encode(name, "ISO-8859-1")%>" method="post">

  • Date without single quotes in SQL Where clause turns to 00000000. Why?

    The below program works in 4.6c but does not in ECC 6.0, the issue is the date actually turns to 00000000, debug shows the internal table as having the correct value that was inserted but st05 trace shows that the variable is holding the value 00000000, this works fine when the date is put inside single quotes but the actual program where I have this issue does not warrant adding single quotes. Has someone come across this situation. Any help is appreciated!
    data v_vbeln like vbak-vbeln.
    data: begin of where_tab occurs 0,
          s_date(20) type c,
          end of where_tab.
    where_tab-s_date = 'audat = 19971106'.
    append where_tab.
    select vbeln into v_vbeln from vbak where (where_tab).
      write:/ v_vbeln.
    endselect.

    HI,
    data v_vbeln like vbak-vbeln.
    ******data: begin of where_tab occurs 0,
    ******s_date(20) type c,
    ******end of where_tab.
    ******where_tab-s_date = 'audat = 19971106'.
    ******append where_tab.
    ***** The above statements are not needed for the select query.
    ******select vbeln into v_vbeln from vbak where (where_tab).
    Your select query can be re-written as
    select vbeln into v_vbeln from vbak where audat eq '19971106'.
    write:/ v_vbeln.
    endselect.
    and if your requirement is to check for multiple dates then,
    append them to a select-options and rewrite the select query as
    select vbeln into v_vbeln from vbak where audat IN S_DATE. " S_DATE is your select-options
    Regards
    Sharath

  • XLIFF escaping (single quote)

    i have a resource string that looks like,
    <trans-unit id="...">
    <source>'{0}'</source>
    <target/>
    </trans-unit>
    notice the single quotes around the token. when i do this, the token won't get replaced by MessageFormat.format(). i tried escaping the single quotes like \'{0}\' which had no effect.
    thanks.

    answering my own question ... this has nothing to do w/ XLIFF. looking at the MessageFormat javadocs, there are some rather confusing details about how single quotes are used to escape. it turns out that a double single quote gets a single quote in the output,
    ''{0}''

  • Single quote in  insert statement

    Hi can anybody please tell how to insert a single quote in value say insert into ex values('example's')

    Hi
    insert into ex values('example''s')
    Sam

  • Quote in sql statements

    hi, i have a problem when i try to enter a word with quotation mark in the query, it gets a java.sql.SQLException: Syntax error or access violation error.
    for example here is my select statement:
    "Select * from tblholdings where title like '"+key+'"";
    If i enter computer as key value it is Ok, but when i enter computer' (with quotation) it get the SQLException error. Please help me on how to solve it. Ho w can i convert the key value with a quotation marks to a value that is acceptable by MySQL database.
    Thanks in advance for your help.

    There are a variety of solutions. I believe the most practical is to use a PreparedStatement rather then a Statement when making the query. A PreparedStatement will automatically escape quotations marks in the query string (if that is your problem).

  • Help with sql insert single quotes

    String insert = "INSERT INTO users(firstName, lastName, emailAdd, password) VALUES("+ firstNameForm + "," + lastNameForm + "," + emailForm + "," + passwordForm + ")";
    Statement stmt = conn.createStatement();
         int ResultSet = stmt.executeUpdate(insert);
    I have that sql insert statment in my servlet the servlet compiles fine but does not insert into the users table, i have been told that it is something to do with single quotes in sql statement, can anybody help me out?

    Or can i change my sql table is there a autonumber which would increase everytime this servlet runs?make your field autoincrement :-)
    example
    ALTER TABLE `users` CHANGE `user_id` `user_id` INT( 10 ) UNSIGNED DEFAULT '0' NOT NULL AUTO_INCREMENT To insert record in the table.
    example:
    you have a table test and got two fields,
    id = (INT) autoincrement
    name = VARCHAR / TEXT etc.
    to insert data to the table test try something like this:
    String SQLStatement = "INSERT INTO test";
    SQLStatement += "(name)";
    SQLStatement += " VALUES (?)";
    statement = Conn.prepareStatement(SQLStatement);
    statement.setString(1, "Duke");
    statement.executeUpdate();
    statement.close();
    Conn.close();Note we dont provide the field for id on our sql statement since it is set as auto-increment ;-)
    regards,
    Message was edited by:
    jie2ee

  • How to deal with single quote (') in a field value?

    I can successfully insert value with single quoet using
    Prepared statement with placeholder(?) construct .
    I can also successfuly use value with single quote(') in
    WHERE clause.
    My question is, is there a way to use string with single
    quote if a Statement like:
    String slqString ="INSERT INTO customers (name, address) VALUES ( 'O'Reilly Bob', 'St Mary's Street') ";
    Statement sqlStmt = con.createStatement();
    sqlStmt.executeUpdate(sqlString);
    The last statement will thow an SQLException because due to single quotes
    Any ideas?

    I think the question was regarding the ' in O'Reily. Use ' twice when using the Statement interface, i.e.
    ("O''Reilly Bob", "St Mary''s Street")
    So that's two single quotes, not a double quote, to successfully insert a single quote, if you know what I mean....
    But like you said PreparedStatement does things like this for you.

  • Single quote in url

    We are using the following configuration in our env...
    Sun web server 6.1 - webserver
    Sun appserver 9.1 EE -application server
    the application server instances are configured with the webserver via loadbalancer plugin.
    If the url contains single quote (%27) the webserver redirects the GET request to a 302 and displaysthe default 404 error page in webserver's docroot
    However, if the issue the same url (with %27) to the appserver, the designated web page is displayed.
    To test the above..
    Try the following
    http://<webserver>:<port>/index.html
    This displays the webserver welcome page
    http://<webserver>:<port>/index.html?test=a
    This displays the webserver welcome page, there is no change
    Now try this
    http://<webserver>:<port>/index.html?test=a%27s
    This will result in the webserver doing a 302 and redirectig to the configured error page..
    Why is this happening, how can we control this.. there cud be escaped single quotes in the URL, which we cannot control
    regds,
    Chiths

    Hi,
    I could not reproduce this with a standalone web server instance. I tried with Web Server 6.1 as well as 7.0 Update 2 release.
    http://<Host>:<Port>/index.html?test=a%27s
    shows me the index.html page fine.
    I tried http://<Host>:<Port>/index.html?test=a's
    as well. This also shows me index.html.
    Can you check if you can reproduce with your standalone web server instance? BTW, Which SP are you using?

  • How to escape a single quotes from a string of dynamic sql clause?

    if a single quotes exist in a dynamic sql clause for a string,
    like
    v_string :='select tname from tab where tabtype='table'',
    there tabtype='table' will conflict with the single quote ahead.
    could somebody tell me how to escape this single quotes?
    thanks for your tips,
    frederick

    fredrick,
    To represent one single quotation mark within a literal, enter two single quotation marks. For example :
    v_string :='select tname from tab where tabtype=''table'''
    Regards,
    Srinivas

  • How to escape a single quote in a find mode view

    Hello,
    I'm working with JDeveloper 10g.
    I've defined a view that is used in "find mode" in a JSP.
    When a value with a single quote is inserted in a field of the search form, an exception is thrown:
    JBO-27122: SQL error during statement preparation.
    ORA-00907: missing right parenthesis.
    The problem is that the "single quote" is not being escaped:
    WHERE STREET LIKE 'ABAT ESCARRE, DE L'A'
    How could I force the view to escape the "single quote"?
    Thanks

    Arrest the single quote by calling a javascript method.
    This might help you
    Re: af:clientListener javascript function call question
    http://download.oracle.com/docs/cd/E12839_01/apirefs.1111/e12419/tagdoc/af_clientListener.html
    Edited by: Srinidhi on Mar 23, 2011 3:46 PM

Maybe you are looking for

  • How to find which user has killed a particular job in CPS?

    Hi All, I am new in CPS. I want to find the user who has killed a particular job in CPS? Thanks in Advance. Avdhesh

  • Safari keeps crashing and breaking my heart

    Hello smart computer fixers! This problem just started this afternoon. I had Safari open and it quit unexpectedly, which happens occasionally, so I started it up again, only to have it quit unexpectedly. It will stay on a website for a few seconds be

  • Comma in long text of routing comma is appearing sepecial character

    Hi Experts, When I am trying to insert comma in long text of routing comma is appearing as sepecial character like <<,>> in long text preview. Please advice how insert comma. Regards, Sandy Edited by: Sandy2 on Apr 20, 2011 10:30 AM

  • Several items to be updated

    Dear BlackBerry team, The BlackBerry q10 is an amazing phone, it has everything one needs. However, somethings could be added and adjusted, like when I'm in the phone app and want to view my contacts from inside it, it doesn't work unless I restart m

  • Fcp liscense key

    hi i have an upgrade license key from final cut studio pro 2 and am traveling and need to install the program on my new laptop. my question is if the FCP Studio 2 full version install DVD's will work with my upgrade license key or are the license key