java模糊查询
String sql = "select con from table_name where con like '%?% ' "; // ?号是占位符
PreparedStatement prepare = conn.prepareStatement(sql);
prepare.setString(1, "a ");
会报错:
java.sql.SQLException: [Microsoft][SQLServer 2000 Driver for JDBC]Invalid parameter binding(s).
当用 String con = "a ";
sql = "select con from table_name where con like '% "+ con + "% ' ";
prepare.executeQuery();
时,就不会报错了.
为什么在关键字 'like '后面用占位符的时候就会出错呢?
------解决方案--------------------String sql = "select con from table_name where con like ? "; // ?号是占位符
PreparedStatement prepare = conn.prepareStatement(sql);
prepare.setString(1, "%a% ");
that 's all!
------解决方案-------------------- '%?% ',这样写?号只是字符串%?%中的一个字符,并不是占位符,没有了占位符prepare.setString(1, "a ")时就找不到对应的占位符了。
String sql = "select con from table_name where con like ? "; // ?号是占位符
PreparedStatement prepare = conn.prepareStatement(sql);
prepare.setString(1, "% "+con+ "% ");//con作为参数传进来