somejkuser
somejkuser

Reputation: 9030

Escaping an apostrophe in Java

I'm still somewhat new to Java and trying to insert data into a database. I'm getting an error when inserting a string containing 's so my end result would be to escape the apostrophe. How can I accomplish?

Upvotes: 2

Views: 8702

Answers (7)

Venkat
Venkat

Reputation: 157

Refer Escape Apostrophe automatically using my Reflect util class. Soon I will share entire library.

/**
 * An automated Sql Escape Apostrophe before preparing an Object as Sql insert
 * query
 * 
 * @param obj
 * @return List of all field's values as string type
 */
public static Object escapeSql_Apostrophe(Object obj) {
    List<Field> fields = getDeclaredFields(obj);
    for (Field field : fields) {
        field.setAccessible(true); // Additional line
        String val = new String();
        // System.out.println("type : " + field.getType().getSimpleName());
        if (isPredfinedObject(field)) {
            try {
                val = field.get(obj) + "";
                if (val.contains("'")) {
                    val = val.replaceAll("'", "''");
                    String type = field.getType().getSimpleName();
                    if (type.equals(String.class.getSimpleName())) {
                        field.set(obj, val);
                    }
                    if (type.equals(Character.class.getSimpleName())) {
                        field.setChar(obj, val.charAt(0));
                    }
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            try {
                System.out.println(field.get(obj));
                System.out.println(getAllFieldsValues(field.get(obj)));
                continue;
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
    }
    return obj;
}

Upvotes: 1

RHSeeger
RHSeeger

Reputation: 16262

Using StringEscapeUtils :

StringEscapeUtils.escapeSql(yourstring);

Caution : As of Commons Lang 3.0 :

StringEscapeUtils.escapeSql

This was a misleading method, only handling the simplest of possible SQL cases. As SQL is not Lang's focus, it didn't make sense to maintain this method.

Upvotes: 5

Kaleb Brasee
Kaleb Brasee

Reputation: 51915

I assume you are using a java.sql.Statement, and calling the executeQuery method with a String. That's bad, because it's possible to do SQL injection. You should use a java.sql.PreparedStatement instead, and then you can set any String that you want as a parameter, and you won't have your problem.

For example:

PreparedStatement pstmt = con.prepareStatement("UPDATE MY_TABLE SET TEXT_FIELD = ?");
pstmt.setString(1, "any String 'will work here!");

Upvotes: 1

Yishai
Yishai

Reputation: 91871

The issue really isn't with Java, rather with the underlying database. Most likely you are stringing your parameters together like this:

  String sql = "select * from sometable where somefield = " + someObject.getSomeField();

Don't do that. Use PreparedStatement's instead.

That has the added advantage of preventing SQL injection attacks, if this is an application that has to be concerned about such things.

Upvotes: 7

jqa
jqa

Reputation: 1370

Use prepared statements. As well as handling any special characters, they are much more robust and help prevent sql injection attacks.

Upvotes: 13

Michael Todd
Michael Todd

Reputation: 17041

Depends on the database, but you can use '' in SqlServer.

EDIT: In MySql you can use a double apostrophe or backslash: http://www.faqts.com/knowledge_base/view.phtml/aid/630

Upvotes: 2

Chris K
Chris K

Reputation: 12341

That's dependent on the database you are using. Usually '' works (I only have firsthand knowledge with SQL Server).

What database are you using?

Upvotes: 0

Related Questions