Tuesday 25 September 2012

How to insert values with single quote in MySQL 5.1 DB using Java PreparedStatement.



Solution: It is as simple as

Replace single quote (‘) with UNICODE (\u2019) value and then pass it to the prepared statement with a bind variable.

Sample Code:

String name = ‘O'Connor’;
String newName = name.replaceAll("'", "\u2019");
String insertQuery = “INSERT INTO TABLE_NAME (COLUMN_NAME)VALUES (?)";
try {
                conn = getConnection();
                pstmt = conn.prepareStatement(insertQuery);
                pstmt.setString(1, newName);
                int count = pstmt.executeUpdate();
    }

2 comments:

  1. I have the same issues and struggling for few days. The blog post got resolved. Thanks for saving my time and posting your experiences.

    ReplyDelete
  2. Thanks a lot for helping me solve my issue in such an easy way.Keep writing!!

    ReplyDelete