String sql="select * from A where name='%?%'"
 PreparedStatement ps=con.prepareStatement(sql);
 ps.setString(1, "张三");这样写是不是会出问题啊?
这样应该怎么解决?如果我是写的一个公共的方法怎么办?例如: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);
  }如果这个时候有一个或两个参数要用通配符……那应该怎么办啊?

解决方案 »

  1.   

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

  2.   

     String sql="select * from A where name=?"
     PreparedStatement ps=con.prepareStatement(sql);
     ps.setString(1, "张三");
    还有下面那段感觉没什么问题啊
      

  3.   

    上述正解如果你想要即进行精确查询又进行模糊查询的话,你的公共方法是不正确的我想,如果你加入一个参数
    public void update(String sql, String param[],String type) throws Exception {
        Connection con = getCon();
        PreparedStatement ps = con.prepareStatement(sql);
        if(type.equals("模糊")){
          for (int i = 0; i < param.length; i++) {
          ps.setString(i + 1, "%"+param[i]+"%");
          }
        }else if(type.equals("精确")){
          for (int i = 0; i < param.length; i++) {
          ps.setString(i + 1, param[i]);
          }   }
            ps.execute();
        closeAll(null, ps, con);
      }