日期:2014-05-20  浏览次数:20639 次

对于PreparedStatement对象和SQL中通配符一起使用的问题
Java code

 String sql="select * from A where name='%?%'"
 PreparedStatement ps=con.prepareStatement(sql);
 ps.setString(1, "张三");


这样写是不是会出问题啊?
这样应该怎么解决?

如果我是写的一个公共的方法怎么办?例如:
Java code

public void update(String sql, String param[]) throws Exception {
    Connection con = getCon();
    PreparedStatement ps = con.prepareStatement(sql);
    for (int i = 0; i < param.length; i++) {
      ps.setString(i + 1, param[i]);
    }
    ps.execute();
    closeAll(null, ps, con);
  }


如果这个时候有一个或两个参数要用通配符……那应该怎么办啊?

------解决方案--------------------
String sql = "select * from A where name like ? and password like ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "%" + "test" + "%");
ps.setString(1, "%" + "test" + "%");
把整个字串提出来设置.
------解决方案--------------------
探讨
String sql = "select * from A where name like ? and password like ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, "%" + "test" + "%");
ps.setString(1, "%" + "test" + "%");
把整个字串提出来设置.