Search code examples
javasqlapostrophe

APOSTROPHE issue with java and SQL


I have code, where I have single quote or APOSTROPHE in my search

I have database which is having test table and in name column of value is "my'test"

When running

SELECT * from test WHERE name = 'my''test';

this works fine

If I use the same in a Java program I am not getting any error or any result

But If I give the name with only single quote then it works

SELECT * from test WHERE name = 'my'test';

Could you please help me out to understand.

Java code is

    Connection con = null;
    PreparedStatement prSt = null;
    try {
        Class.forName("oracle.jdbc.driver.OracleDriver");
        con = DriverManager.
            getConnection("jdbc:oracle:thin:@localhost:1521:orcl"
                ,"user","pwd");
        String query = "SELECT * from "
                + "WHERE name = ? ";
        prSt = con.prepareStatement(query);

        String value = "my'mobile";
        char content[] = new char[value.length()];
        value.getChars(0, value.length(), content, 0);
        StringBuffer result = new StringBuffer(content.length + 50);
        for (int i = 0; i < content.length; i++) {
            if (content[i] == '\'')
            {
                result.append("\'");
                result.append("\'");
            }
            else
            {
            result.append(content[i]);
            }
        }
        prSt.setObject(1, result.toString());
        int count = prSt.executeUpdate();
        System.out.println("===============>    "+count);
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    } finally{
        try{
            if(prSt != null) prSt.close();
            if(con != null) con.close();
        } catch(Exception ex){}
    }

Solution

  • You don't have to escape anything for the parameter of a PreparedStatement

    Just use:

    prSt = con.prepareStatement(query);
    prSt.setString("my'mobile");
    

    Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()

    ResultSet rs = prst.executeQuery();
    while (rs.next())
    {
       // process the result here
    }
    

    You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html