Sunday, October 30, 2011

Issues with apostrophe symbol as part of document name


Problem Statement:
quoted string not properly terminated.

Ok, what is the bug here?
Application is not getting the documents which are related to the specific model.

How the problem was identified?
I have gone through the log files to know the origin of the problem.  Log file is getting updated with the above specified error.  Later, I have tried to replicate the same issue with a sample program.  Finally, I came to know that the issue is related to Java’s Statement interface.  If we want to use apostrophe in middle of SQL statement, we should specify another apostrophe.  If we prepare SQL statement with Java's Statement interface, we should care about this apostrophe issue.  If we use Java's PreparedStatement instead of Java's Statement, we need not worry about this issue.  Java takes care about this.

Solution provided:

Quick solution provided:
I have updated the database by removing the special character.

Suggested solution: I have updated the java code as below.

Previous Code: -
Statement stmt = con.createStatement();
String sQueryDocData = "SELECT * FROM DOC_ATTACHMENTS WHERE DOC_ID = "+ docId +" AND DOC_ATTACH_NAME = '" + sDocAttchName +"'";
ResultSet rs = stmt.executeQuery(sQueryDocData);

Updated Code: -
PreparedStatement pstmt = con.prepareStatement("SELECT * FROM DOC_ATTACHMENT WHERE DOC_ID = ? AND DOC_ATTACH_NAME = ?");
pstmt.setInt(1, docId);
pstmt.setString(2, sDocAttchName);
ResultSet rs = pstmt.executeQuery();

For Example: - String sDocAttachName = "doc's.txt";