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.

Similar Messages

  • 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

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

  • 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

  • String with embedded single quote

    Hi, all. We're trying to pass a string from one procedure to another, which will then do an EXECUTE IMMEDIATE on it. However, there are single quotes withing the string, and they're driving us nuts! This is what the concatenated string should look like when passed to the pw_execDDL procedure:
    insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values ('MEAG', to_date('02-OCT-05','DD-MMM-YY'), 'Y',1);
    Here's the concatenation process that doesn't work, and there are functions being called within the string:
    chr_sql := 'insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values (' || '''' || prm_inoc_id || '''' || ', ' || 'to_date(' || '''' || prm_proof1 || ''''||','||'''' ||'DD-MMM-YY'||''''||')' || ', ' || '''' || fw_is_proof_valid(prm_birth_date, prm_proof1) || '''' || ',1);';
    pw_execDDL(chr_sql); /* call the procedure to do the EXECUTE IMMEDIATE */
    Help! We've tried every combination -- using two single quotes together, three, and four, and still no luck. Thanks.

    insert into appimmunization.wsrprfs (inoc_id, proof,
    is_valid,proof_num) values ('MEAG',
    to_date('02-OCT-05','DD-MMM-YY'), 'Y',1);
    This statement can be made in a string with the following affectation:
    chr_sql := 'insert into appimmunization.wsrprfs (inoc_id, proof, is_valid,proof_num) values (''MEAG'', to_date(''02-OCT-05'',''DD-MMM-YY''), ''Y'',1)';
    Note please that each single quote in your original string must be specified using two single quotes and that is all. It is more readable and more easy to do it this way.
    Michel.

  • 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

  • Problem in retrieving LONG(of Oracle) column in Java String Object

    Hi,
    I wrote some codes to fetch some columns into a String array(two dimentional), one of the column is long (in Oracle database)...whenever I try to get the value into the array..its showing
    java.sql.SQLException: Stream has already been closed
    Some where I read that I've to fetch the long column first..now this was my general function...the resultset can have more than one rows..in that case, how can I retrieve the long data first. Now next time(for the second row) in the loop..it'll get LONG(as it'll be first to retrive) after some normal column(from the first column)...again it can show the same problem.
    Is there any concrete solution for that? Please help me to sort this out.
    Thanks in advance.
    ---Sourav

    Hi Gurus,
    Please reply..
    Thanks and Regards,
    MSORA

  • How to search the location of the single quote using instr func in a string

    I have a string '345634','234'(all 4 single quotes are part of the string) and I want to find the location of the 3rd single quote using the instr function , could sum1 quickly please help me out.
    Regards
    Rahul
    Edited by: Rahul Kalra on Aug 26, 2010 8:58 AM

    Carlovski wrote:
    You really do learn something new every day!
    It really is quite ugly syntax though.Not really. You can use whatever character you want to indicate the start and end of the string, but if you use any of the brackets "[", "(" or "{" you should terminate using the opposing bracket "]", ")" or "}" respectively. It also looks a bit more ugly with data like that, but if you are entering regular text then it looks ok...
    e.g.
    SQL> select q'[This is my string with fred's quotes in it]' as mystring from dual;
    MYSTRING
    This is my string with fred's quotes in it
    SQL> select q'(This is my string with fred's quotes in it)' as mystring from dual;
    MYSTRING
    This is my string with fred's quotes in it
    SQL> select q'{This is my string with fred's quotes in it}' as mystring from dual;
    MYSTRING
    This is my string with fred's quotes in it
    SQL> select q'.This is my string with fred's quotes in it.' as mystring from dual;
    MYSTRING
    This is my string with fred's quotes in it
    SQL> select q'#This is my string with fred's quotes in it#' as mystring from dual;
    MYSTRING
    This is my string with fred's quotes in it
    SQL> select q'`This is my string with fred's quotes in it`' as mystring from dual;
    MYSTRING
    This is my string with fred's quotes in it
    SQL>Well... almost any character...
    SQL> select q'¼This is my string with fred's quotes in it¼' as mystring from dual;
    ERROR:
    ORA-01756: quoted string not properly terminated

  • FYI: Single Quote in column comment problem

    SQL Developer Version 1.1.0.23 on Windows XP
    If you have a single quote in a column comment and you click on the SQL tab for the table it does not generate two single quotes for each quote in the comment. This generates a syntactically incorrect COMMENT ON COLUMN statement and messes up the rest of the generated statements.
    Mike

    I am just too far into my project...and it is my first one (it is quite a big project ),and going back to preparedstatement will be quite time consuming.
    So indirectly,there is no one statement or inbuilt java methods which takes care of this quote ? I wish there was.
    Thanks.

  • 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

  • Passing value in procedure with single quotes intact

    HI,
    I have the following procedure.
    create or replace procedure p1( a varchar2) is
    begin
    execute immediate ' update emp set sal = 20*Sal + sal
    where ename like ' || a;
    end;
    when I try to run this and pass a value to a. the single quotes
    r removed and the entire string becomes.
    'update emp set sal = 20*sal + sal where ename like scott'
    hence the error.
    now my problem is how can i make sure the scott goes like 'scott'
    i.e the single quotes are intact. or otherwise 'scott%'
    thanx in advance
    Sreekant Vadlamani

    You can also use triple quotes to do this. the effects of
    multiple quotes can be seen below. The same stuff works in
    procedures
    Connected to:
    Oracle8i Enterprise Edition Release 8.1.5.0.0 - Production
    With the Partitioning and Java options
    PL/SQL Release 8.1.5.0.0 - Production
    SQL> select 'hello' from dual;
    'HELL
    hello
    SQL> select ''hello'' from dual;
    select ''hello'' from dual
    ERROR at line 1:
    ORA-00923: FROM keyword not found where expected
    SQL> select '''hello''' from dual;
    '''HELL
    'hello'
    SQL> select ''''hello'''' from dual;
    select ''''hello'''' from dual
    ERROR at line 1:
    ORA-00923: FROM keyword not found where expected
    SQL> select '''''hello''''' from dual;
    '''''HELL
    ''hello''
    SQL>

  • REGEXP_LIKE help with literal single-quote

    I'm trying to write a check constraint to validate email addresses that may include an apostrophe in the email address. Such as joe.o'[email protected] Here is my sample setup:
    create table emails
    ( email_address varchar2(150)
    insert into emails values('[email protected]') ;
    insert into emails values('[email protected]') ;
    insert into emails values('joey.o''[email protected]') ;
    commit;
    sql> select * from emails;
    EMAIL_ADDRESS
    [email protected]
    [email protected]
    joey.o'[email protected]
    alter table emails add constraint email_address_format_ck
        CHECK ( REGEXP_LIKE ( email_address, '^[a-z0-9._%-]\'?+@[a-z0-9._%-]+\.mil$','c'));
    ERROR at line 2:
    ORA-00911: invalid characterIt doesn't like *\'?*
    My understanding is this means one or more single-quotes. Anyone know the correct syntax to accept apostrophes?

    Hi,
    jimmyb wrote:
    ... insert into emails values('joey.o''[email protected]') ;
    That's the correct way (actually, that's one correct way) to include a single-quote in a string literal: use 2 single-quotes in a row.
    ... alter table emails add constraint email_address_format_ck
    CHECK ( REGEXP_LIKE ( email_address, '^[a-z0-9._%-]\'?+@[a-z0-9._%-]+\.mil$','c'));Here, the 2nd argument to REGEXP_LIKE is a string literal, just like 'joey.o''[email protected]' was a string literal.
    To include a single-quote in the middle of this string literal, do the same thing you did before: use 2 of them in a row:
    CHECK ( REGEXP_LIKE ( email_address, '^[a-z0-9._%''-]+@[a-z0-9._%-]+\.mil$','c'));There were a couple of other problems, too.
    I'm sure you meant for the apostrophe to be inside the square brackets. Inside square brackets, \ does not function as an escape character. (Actually, single-quote has no special meaning in regular expressions, so there's no need to escape it anyway.)
    I'm not sure what the '?' mark was doing; I left it out.
    Of course, you'll have trouble adding the CHECK constraint if any existing rows violate it.
    Edited by: Frank Kulash on Feb 10, 2012 6:52 PM

  • Replace a string single quote(') with underscore(_)

    I have more than 100 tables in a schema.
    I have to find out if a string has a single quote in the column and replace it with an underscore.
    I have 2 columns CREATE_USER and UPDATE_USER in all the tables. Now i want to update the values if the string has a single quote in it.
    I tried it with execute immediate but it is not allowing underscore in the statement.
    DECLARE
       v_table_name    VARCHAR2 (30);
       v_column_name   VARCHAR2 (30);
       CURSOR c_name
       IS
          SELECT DISTINCT table_name, column_name
                     FROM user_tab_cols
                    WHERE column_name IN ('LOGIN', 'CREATE_USER', 'UPDATE_USER')
                      AND table_name NOT LIKE '%JN';
    BEGIN
       FOR rec IN c_name
       LOOP
          v_table_name     := rec.table_name;
          v_column_name    := rec.column_name;
          EXECUTE IMMEDIATE    'update '
                            || v_table_name
                            || ' set '
                            || v_column_name
                            || ' = REPLACE('
                            || v_column_name
                            || ','''',"_") where '
                            || v_column_name
                            || ' like "%''%"';
       END LOOP;
    END;
    /i am getting the below error:
    ORA-00904: "%'%": invalid identifier
    ORA-06512: at line 17Can anyone let me know what is the error in the statement and how to overcome it

    please try to replace your execute immediate with:
    EXECUTE IMMEDIATE  'update '
                            || v_table_name
                            || ' set '
                            || v_column_name
                            || ' = REPLACE('
                            || v_column_name
                            || ','''''''',''_'') where '
                            || v_column_name
                            || ' like ''%''''%''';You can check the statement when you take a look at the construction before like this:
    declare
      v_sql varchar2(1000);
    begin
       v_sql:= 'update '
                            || v_table_name
                            || ' set '
                            || v_column_name
                            || ' = REPLACE('
                            || v_column_name
                            || ','''''''',''_'') where '
                            || v_column_name
                            || ' like ''%''''%''';
       dbms_output.put_line(v_sql);
       execute immediate v_sql;
       ...Edited by: hm on 23.11.2010 01:43

  • Single quote used with in text data renders to inalid display

    I have the following text snipit that is coming from an Oracle database column: ...did not include 'special decontamination'. New ...
    I am putting this into a pretty standard text object.  When the report is previewed and subsequently printed as a PDF each single quote is transformed to the text string &_#_3_9_; code (without the underscores). This also occurs for quotation marks appearing as &_q_u_o_t_; and ampersands appearing as &_;_a_m_p_;
    I've tried changing the text interpretation property from none to rtf and, with a refresh, nothing changed.  It is hard for me to believe that no one else has seen this but since you can not search the forum for this string (as it converts it to the single quote) may not one has asked.
    Thanks in advance.

    Hi Don,
    The CLOB would do it. 
    Not sure there is a way around this aside from how you've already been dealing with it. 
    To simply your formula a bit, you don't need to do a loop just have it check for each of the tags like:
    stringVar TempText := {PPR_Main.CONCERNS};
    TempText := Replace (TempText, '&_#_3_9_;', "'") ;
    TempText := Replace (TempText, '&_;_a_m_p_', "&") ;
    TempText := Replace (TempText, '&_q_u_o_t_;', '"') ;
    TempText
    I agree though that there may be other tags added later on based on other characters so it could be infinite.  Try the common characters like Exclamation and Question marks. 
    Good luck,
    Brian

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

Maybe you are looking for