preparedStatement一个小技巧

preparedstatement的sql语句不能用?=?,想要用的话用如下方法

 

 

DBconn DB = new DBconn();
     Connection con = DB.getConn();
     String sql = "SELECT * FROM server,node WHERE server.node_id=node.id GROUP BY hostname;";
     String sqlss = "select * from server,node where server.node_id=node.id and %column%=?;";//加百分号是为了让字符串唯一,防止替换了相同的字符串。比如mycolumn
     
     try{
     
      String accord = request.getParameter("accord");      
      String find = request.getParameter("find");
      PreparedStatement pstmt = null;
      ResultSet rs = null;
      
      if( accord !=null){
      
       pstmt = con.prepareStatement(sqlss.replace("%column%",accord));
        
      }
      Statement stmt = con.createStatement();
    
      System.out.println(accord);
      System.out.println(find);
      
      if(find != null){       
       pstmt.setString(1,find);
       rs = pstmt.executeQuery();
       System.out.println(sqlss);
      }else{
       rs = stmt.executeQuery(sql);
      }

posted on 2010-08-03 17:45  Miracle刘  阅读(125)  评论(0编辑  收藏  举报