當我們需要開發一個方法用來查詢資料庫的時候,往往會遇到這樣一個問題:就是不知道用戶到底會輸入什麼條件,那麼怎麼樣處理sql語句才能讓我們開發的方法不管接受到什麼樣的條件都可以正常工作呢?這時where '1'='1'加上list就可以完美解決這個問題了,廢話少說,上代碼: **註解: 1,以上代碼操 ...
當我們需要開發一個方法用來查詢資料庫的時候,往往會遇到這樣一個問題:就是不知道用戶到底會輸入什麼條件,那麼怎麼樣處理sql語句才能讓我們開發的方法不管接受到什麼樣的條件都可以正常工作呢?這時where '1'='1'加上list就可以完美解決這個問題了,廢話少說,上代碼:
1 // 模糊查詢方法 2 public List<person> query() { 3 List<person> list = new ArrayList<>(); 4 Connection con = null; 5 Scanner sc = new Scanner(System.in); 6 System.err.println("enter name:"); 7 String name = sc.nextLine(); 8 System.err.println("enter id:"); 9 String id = sc.nextLine(); 10 System.err.println("enter tel:"); 11 String tel = sc.nextLine(); 12 System.err.println("enter sex:"); 13 String sex = sc.nextLine(); 14 String sql = "select id,name,tel,sex from students " 15 // 技巧在此,合理拼接字元串 16 + "where 1=1"; 17 List<Object> list1 = new ArrayList<Object>(); 18 //使用 commons-lang包 19 if (StringUtils.isNotEmpty(name)) { 20 sql += " and title like ?"; 21 list1.add("%" + name + "%"); 22 } 23 24 if (!StringUtils.isEmpty(id)) { 25 sql += " and content like ?"; 26 list1.add("%" + id + "%"); 27 } 28 29 if (!StringUtils.isEmpty(tel)) { 30 sql += " and addr like ?"; 31 list1.add("%" + tel + "%"); 32 } 33 try { 34 con = DSUtlis.getConnection(); 35 // SQL語句組成完成以後,就生成pst對象 36 PreparedStatement pst = con.prepareStatement(sql); 37 // 設置?的值 38 for (int i = 0; i < list1.size(); i++) { 39 pst.setObject(i + 1, list.get(i)); 40 } 41 ResultSet rs = pst.executeQuery(); 42 while (rs.next()) { 43 person p = new person(); 44 p.setId(rs.getString("id")); 45 p.setName(rs.getString("name")); 46 p.setTel(rs.getString("tel")); 47 p.setSex(rs.getString("sex").equals("1") ? "男" : "女"); 48 list.add(p); 49 } 50 rs.close(); 51 pst.close(); 52 } catch (Exception e) { 53 e.printStackTrace(); 54 } finally { 55 try { 56 con.close(); 57 } catch (SQLException e) { 58 e.printStackTrace(); 59 } 60 } 61 return list; 62 }
**註解:
1,以上代碼操作一個Oracle資料庫:
create table students( id varchar(32), name varchar(30), tel varcher(15), sex char(1), constraint stud_pk primary key(id) );
2,使用工具類獲取Connection
3,proson是一個javabean