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.

Similar Messages

  • 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)))

  • 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">

  • 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

  • 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)))

  • 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 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 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

  • Single Quote Escaping in ColdFusion 8

    Recently we've begun migrating some sites to ColdFusion 8
    from earlier versions of ColdFusion. We've found the following
    quirk when inserting data into an SQL database.
    <cfset value = "Two single quotes '' and one single quote
    ' in the same line does not insert as expected." />
    <cfquery datasource="#datasource#">
    UPDATE Record
    SET field = '#value#'
    </cfquery>
    Running the code above updated the record in the database to
    be "Two single quotes ' and one single quote ' in the same line
    does not insert as expected." In this case it did not escape the
    two single quotes together so only one sigle quote was entered
    there, but where the single quote was by itself it was properly
    escaped and entered into the database record. I would have expected
    the code above to be entered into the database as "Two single
    quotes '' and one single quote ' in the same line does not insert
    as expected." where all single quotes in the string were escaped.
    Has anyone else encountered this problem, and know of a way
    to correct it? The exact same query works as exprected in previous
    versions of ColdFusion. Manually changing all of the existing
    queries on the site to manually escape the single quotes would be
    an incredibly time consuming process, so I'm hoping that there is
    another way around the problem.

    quote:
    Originally posted by:
    swg_mcherry
    Recently we've begun migrating some sites to ColdFusion 8
    from earlier versions of ColdFusion. We've found the following
    quirk when inserting data into an SQL database.
    <cfset value = "Two single quotes '' and one single quote
    ' in the same line does not insert as expected." />
    <cfquery datasource="#datasource#">
    UPDATE Record
    SET field = '#value#'
    </cfquery>
    Running the code above updated the record in the database to
    be "Two single quotes ' and one single quote ' in the same line
    does not insert as expected." In this case it did not escape the
    two single quotes together so only one sigle quote was entered
    there, but where the single quote was by itself it was properly
    escaped and entered into the database record. I would have expected
    the code above to be entered into the database as "Two single
    quotes '' and one single quote ' in the same line does not insert
    as expected." where all single quotes in the string were escaped.
    Has anyone else encountered this problem, and know of a way
    to correct it? The exact same query works as exprected in previous
    versions of ColdFusion. Manually changing all of the existing
    queries on the site to manually escape the single quotes would be
    an incredibly time consuming process, so I'm hoping that there is
    another way around the problem.
    With that specific example, let's say value = O'Hara. This is
    what I have noticed over time.
    set field = '#value#' would crash because your database would
    see 3 single quotes.
    set field = '#replace(value, "'", "''", "all")#' would work,
    but your database record would be O'Hara, not O''Hara as you said
    you would expect.

  • How to escape the single quote from email value?

    Hi,
    Is there any way to escape the special character single quote from the email value.
           String ownerQry = "Select Id, email from User where email in('0000'";
            for(int i=0; i<accountData.length; i++)
                ownerQry += ",'" + accountData.TEAM_EMAIL+"'";
    ownerQry += ")";
    QueryResult qrTeam = sfdcCtrl.query(ownerQry);
    When i tried to set the email value on a custom object, its throwing the error as below  and failed to update. <xml-fragment xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:sf="urn:fault.enterprise.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"><faultcode>sf:MALFORMED_QUERY</faultcode><faultstring>MALFORMED_QUERY:
    '[email protected]','brenden.o'[email protected]','[email protected]'
    ^ ERROR at Row:1:Column:963 expecting a right parentheses, found 'connor'</faultstring><detail><sf:fault xsi:type="sf:MalformedQueryFault" xmlns:sf="urn:fault.enterprise.soap.sforce.com"><sf:exceptionCode xmlns:sf="urn:fault.enterprise.soap.sforce.com">MALFORMED_QUERY</sf:exceptionCode><sf:exceptionMessage xmlns:sf="urn:fault.enterprise.soap.sforce.com">
    '[email protected]','brenden.o'[email protected]','[email protected]'
    ^ ERROR at Row:1:Column:963 expecting a right parentheses, found 'connor'</sf:exceptionMessage><sf:row xmlns:sf="urn:fault.enterprise.soap.sforce.com">1</sf:row><sf:column xmlns:sf="urn:fault.enterprise.soap.sforce.com">963</sf:column></sf:fault></detail></xml-fragment>

    Thanks Dr.Clap.
    I think its very tricky to implement this.
    Here is the SOQL query. i am passing all the email values.
    Select Id, email from User where email in('0000','o\'[email protected]','[email protected]')
    These values are coming from oracle DB table in the form of array accountData[].TEAM_EMAIL
            String ownerQry = "Select Id, email from User where email in('0000'";
            for(int i=0; i<accountData.length; i++)
               ownerQry += ",'" + accountData.TEAM_EMAIL+"'";
    ownerQry += ")";the array value may contain the email with single quote before @gmail.com which i need to ignore. :-( i think this is very tricky. who knows the solution for this?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • 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

  • Report parameter field value has a single quote. need to escape before pass

    Report has a parameter whose value might have a single quote in it. If I pass that value directly into the SQL Command... like
    where ... user_name = {?parm_user_name}...
    which would translate to
    user_name='O'Donnel Honda'
    I am getting an error... so would like to convert this parameter value into 'O''Donnel Honda' before passing into the query.
    I created a formula called parse_user_name with following:
    Replace ({?parm_user_name}, "'", "''")
    And used in the query like
    where ... user_name = {@parse_user_name}...
    I am getting an error like invalid SQL92 character...

    I think you should use the condition like this
    where ... user_name = '{?parm_user_name}'
    keep the parameter in single quote at the command level itself.
    Now use the same formula like
    replace({?Parameter},"'","''")
    This works only if the parameter is a single value parameter but not multi value parameter.
    Regards,
    Raghavendra

  • SSAS SSRS Report Action on Cell Value w/ Embedded Single Quote Not Executing

    I have configured an SSAS 2008 R2 cube SSRS ReportAction. I'm having problems when the member value for a cell has an embedded single quote, e.g. abc's. The action displays on the context menu appropriately, but when I click on the action, nothing happens.
    For member values that do not have the single quote, the action works as designed. I've added a calculated ember to escape the embedded single quote by adding another single quote, e.g. abc''s, with no luck. Is there a resolution or workaround for this?

    Hi Mdccuber,
    According to your description, you create a reporting action in you cube, and it works fine except the members that have embedded single quote, right? In your scenario, it seems that you pass this value to the report as the parameter.
    In SQL Server Analysis Services (SSAS), when pass values to a report, multi-select parameters have to be placed into IN statement and SQL Server Reporting Services (SSRS) will do single-quote wrapping for string values automatically. In this case, the original
    value that have embedded single quote will be damaged. So this action not work. You can submit a feedback at
    http://connect.microsoft.com/SQLServer/Feedback and hope it is resolved in the next release of service pack or product.
    Regards,
    Charlie Liao
    TechNet Community Support

  • Can we have a Single quote in the tooltip text?

    Hi,
    We have some tooltips for the presentation columns which contains a single quote.
    When I try to view the tooltip from answers the single quote is being replaced by double quotes.
    I tried to use all sorts of escape characters for single quote, like "\'" and ''' and "'" but that didn't work.
    Is there any way to do this.
    Thanks!!
    Vasantha.P

    As I said in my earlier post, I am looking for the tooltips for the Presentation tables and columns. The tooltips for these were extracted from the RPD using the externalize Strings option and these externalized strings are stored in the database.
    So I am escaping the single using a single quote both in rpd and in the database.
    Example text I have used both in the rpd and database is something like "Shipment's start time". I tried with "Shipment''s start time", " Shipment'''s start time", but it didn't work.
    Thanks!!
    Vasantha.P

  • Adding a single quote in the flash chart legend

    Hi all,
    I am using a following code to create a line chart.
    SELECT null link
    ,TO_CHAR(monat, 'MON-YY')
    ,ROUND(No_of_hits/1000) "No of Clicks(''000)"
    FROM
    SELECT DISTINCT TRUNC(ref_month,'MONTH') monat
    ,SUM(no_of_hits) OVER (ORDER BY TRUNC(ref_month,'MONTH') RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) No_of_hits
    FROM goodnews_hits
    WHERE ref_month BETWEEN :p77_DATE_startline
    AND :p77_DATE_endline
    ORDER BY monat;
    I get the following legend in the top region of the chart
    No Of Stories
    No of Clicks(''000)
    I need the No of Clicks to be displayed as
    No of Clicks('000)
    i.e.
    Only one single quote before 000
    Could you please tell me , how this can be achieved?
    Thanks,
    Archana

    As I said in my earlier post, I am looking for the tooltips for the Presentation tables and columns. The tooltips for these were extracted from the RPD using the externalize Strings option and these externalized strings are stored in the database.
    So I am escaping the single using a single quote both in rpd and in the database.
    Example text I have used both in the rpd and database is something like "Shipment's start time". I tried with "Shipment''s start time", " Shipment'''s start time", but it didn't work.
    Thanks!!
    Vasantha.P

Maybe you are looking for