Question

Here its my Query

SQL_QUERY="SELECT review.comment FROM ReviewDO review WHERE title='"+titleName+"'";

By using title am trying to get its description.

For Example if tileName="Worth for money"; (without apostrophe) the query will be:

SQL_QUERY="SELECT review.comment FROM ReviewDO review WHERE title='Worth for money';

am getting the output.

but if titleName="Can't beat the product";(with apostrophe)

SQL_QUERY="SELECT review.comment FROM ReviewDO review WHERE title='Can't beat the product';

am getting org.hibernate.QueryException:expecting ''',found 'EOF'

Is there any way to avoid this problem?

Was it helpful?

Solution

Use placeholders. It will also help in preventing SQL injections:

 Session ses = HibernateUtil.getSessionFactory().openSession();
  String query = "SELECT review.comment FROM ReviewDO review WHERE title=:title";
  List<ReviewComment> reviewComments = ses.createQuery(query)
  .setParameter("title", "Can't beat the product")
  .list();
  ses.close();

And if you are sure that your query will give only one record then instead of using list() use uniqueResult() method of Query interface.

For more details see the documentation of Query interface here

OTHER TIPS

You can use PreparedStatement instead of simple query and let PreparedStatement handles apostrophe and other special characters for you. Refer this Oracle's documentation.

Second way is to use StringEscapeUtils library. Refer the doc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top