Search code examples
javamysqljdbcentitymanager

java- how to check if value exists in JSP page?


I have a function that check if there is a particular record exists in a table in MYSQL.

Below is this code:

public String get_value(long nodeid,String ts) {
    try {
        String sql="Select URL FROM urllink WHERE URL='f0="+nodeid+"&ts="+ts + "'";

        em.createNativeQuery(sql).getSingleResult();
        if (em == null) {
            throw new Exception("could not found URL object.");
        }
      //  return 1;

    } catch (Exception e) {
        e.printStackTrace();



    }
   return null;
}

In my JSP page, I will call this function and pass the parameters to it.

String v=fileFacade1.get_value(fileID,date);

  if(v !=null ){ 

// if the records exist in the table, do this

}

I am trying to call the function so if there is a record in the table,then enter the if statement and do something but from what I debug, the value of v is always null but there is record from the singleresult.

Did I do something wrong?

EDIT:

This is how it looks like now:

public String get_value(long nodeid,String ts) {
    try {
        String sql="Select URL FROM urllink WHERE URL='f0="+nodeid+"&ts="+ts + "'";
        if (em == null) {
            throw new Exception("could not found URL object.");
        }
        em.createNativeQuery(sql).getSingleResult();

        return (String)em.createNativeQuery(sql).getSingleResult();

      //  return 1;

    } catch (Exception e) {
        e.printStackTrace();



    }
  return null;
}

Solution

  • You need to return getSingleResult()

    return (String)em.createNativeQuery(sql).getSingleResult();
    

    Execute a SELECT query that returns a single result.