使用 PreparedStatement 进行模糊查询

使用 PreparedStatement 进行模糊查询的方法和注意事项。 

今天发现有人问这样的问题:在预编译语句中,执行下面的语句出错,

select * from tblcategory,tblproduce
 where tblcategory.category = tblproduce.category and name like '%?%' 
 

这样的问题网上也有很多人问。PreparedStatement的用法和直接的SQL语句是不同的,正确的方法应当是这样写,例如:

String sql = "select * from App_User Where UserName Like ?";
String UserName = "mxh1";
PreparedStatement cmd = cn.prepareStatement(sql);
cmd.setString(1,"%" + UserName + "%");
ResultSet rs = cmd.executeQuery();
while(rs.next())
{
 out.print("<li>UserName = " + rs.getString("UserName"));
}

注意:cmd.setString(1,"%" + UserName + "%"); 中没有原先的单引号,这个一定要记住。

出至[孟子E章]

猜你喜欢

转载自blog.csdn.net/BinGuoLA/article/details/81321783
今日推荐