简体   繁体   中英

Getting exception as I try use the WHERE clause

While trying to execute the query with where clause, I get an exception :

SEVERE: Unknown column 'suhail03' in 'where clause'
org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:67)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
    at org.hibernate.loader.Loader.doList(Loader.java:2223)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2104)
    at org.hibernate.loader.Loader.list(Loader.java:2099)
    at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:378)
            ...

Here suhail03 is the condition in the where clause. Where am I going wrong ?

 private boolean appAuthorized(String username) {

    boolean hasAuthorized = false;
    try {
        Session session = new HVR().getSession();

        String hql = "from UCred where username =" + username; // WHERE QUERY

        List list = session.createQuery(hql).list();
        Iterator iterator = list.iterator();
        while(iterator.hasNext()) {
            UCred user = (UCred)iterator.next();
            if(user.getAccessToken().compareTo("null") == 0) {
                hasAuthorized = false;
            }else {
                hasAuthorized = true;
            }
        }
    }catch(Exception exc) {
        exc.printStackTrace();
        return false;
    }
    return hasAuthorized;

}

Without parameter binding, you have to concatenate the parameter String like this (bad code) :

String hql = "from UCred where username =" + "'" + username + "'";

it's better to use positional parameters

String hql = "from UCred ucred where ucred.username = :username";

List list = session.createQuery(hql).
            .setParameter("username", username)
             .list();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM