Showing posts with label Replace single quote. Show all posts
Showing posts with label Replace single quote. Show all posts

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();
    }