Thread: PreparedStatement with LIKE

PreparedStatement with LIKE

From
Dav Coleman
Date:
I'm having problems getting a PerparedSteatement to work, and I suspect it
is because I am not handling the WHERE col LIKE '%blah%' situation
correctly. I've searched the web for an example but have not found one, can
anyone help?

This is basically what I want to do, change this:

String sql = "SELECT id FROM mytable WHERE name LIKE UPPER('%"+name+"%')";
...
ResultSet rs = st.executeQuery(sql);

to this:

String sql = "SELECT id FROM mytable WHERE name LIKE UPPER(?)";
PreparedStatement pstmt = db.prepareStatement(sql);
pstmt.setString(1, '%'+name+'%' );
ResultSet rs = pstmt.executeQuery(sql);

That doesn't work though, can anyone tell me what would?

My actual SQL query is much more complex, but I think this pares down the
problem to its essence

thanks,
--
Dav Coleman
http://www.danger-island.com/dav/