查询结果遍历处理

第一种遍历,利用了哈希表这样查询了所有结果并放进了HashMap,这样不仅复杂而且查询的效率不高:

PreparedStatement p = conn.prepareStatement("select * from test");
            ResultSet rs = p.executeQuery();
            HashMap<String,String> hm = new HashMap<String, String>();
            while(rs.next())
            {
                hm.put(rs.getString("username"), rs.getString("password"));
            }
            dao.close(rs, p, conn);
            Set<String> set = hm.keySet();
            Iterator<String> it = set.iterator();
            while(it.hasNext())
            {
                if(it.next().equals(user))
                {
                    if(password.equals(hm.get(user)))
                    {
                        rt = true;
                        break;
                    }
                }
            }
  • 第二种遍历查询数据库条件限定了username和password,所以不用完全查询数据库,也不用HashMap,只要结果集有元素就返回true:
PreparedStatement p = conn.prepareStatement("select * from test where username = ? and password = ?");
            p.setString(1, user);
            p.setString(2, password);
            ResultSet rs = p.executeQuery();
            while(rs.next())
            {
                dao.close(rs, p, conn);
                return true;
            }
            dao.close(rs, p, conn);
            return false;

你可能感兴趣的:(遍历,select)