开发者

Java PreparedStatement SQL Syntax for LIKE

开发者 https://www.devze.com 2023-01-30 04:06 出处:网络
I have a prepared statement as so: private static final String SQL_LIST_GROUP = \"SELECT * FROM table

I have a prepared statement as so:

private static final String SQL_LIST_GROUP = "SELECT * 
                                                FROM table 
                                               WHERE group LIKE ?;"

My function, my function is as follow(shortened and SQL objects properly declared):

public List< MyType > getGroupList(Long grp) {  
   Connection link = null;  
    PreparedStatement query = null;    
    ResultSet rstList = null;  
    List< MyType > list = new ArrayList< MyType >();  
    try {  
        link = MySQL.getConnection();    
        link.setAutoCommit(false);  
        query = link.prepareStatement(SQL_LIST_GROUP);  
        query.setString(1, "%"+grp.toString()+",%");  
        rstList = query.executeQuery();  
        link.commit();  
        while (rstList.next()) {  
            list.add(MapFields(rstList));  
        }  
        return list;  
    } catch (S开发者_StackOverflow中文版QLException e) {  
        throw new DAOException(e);  
    } finally {  
        close(link, query, rstList);  
    }  
}

The conections are made properly, but I get a syntax error, the prepared statement with the value parsed is as follows:

"SELECT * 
   FROM table 
  WHERE group LIKE '%grp%';"

Any Suggestions?


I have also seen issues with semi-colons in PreparedStatemts.

Also, the parameter to the method is called 'grp', but 'group' is being used in the call to setString. Is that a type-o, or part of the problem? group.toString() should suffice, no need for the valueOf/longValue stuff.

Another thing, 'group' is a reserved word in MySQL.


I've seen a DB bomb out because of a trailing ; in dynamic SQL before. Does removing that cause it to work?

0

精彩评论

暂无评论...
验证码 换一张
取 消