1

我有一个不寻常的问题,我不知道如何解决。

我有一个编辑页面,用于编辑数据库表中的数据。例如,当用户打开页面时,他会看到输入值90。使用下面的 Java 代码检查输入字段是否重复到 DB 表中。现在问题来了:当用户打开编辑页面并单击提交按钮时,他每次收到消息时都会收到90 is already in use!。我需要找到一个解决方案,如何将原始值传递给验证器,并将值检查到数据库表中。也许这个 sql 查询不正确。

// Validate Datacenter ID

    public void validateDatacenterID(FacesContext context, UIComponent component, Object value) throws ValidatorException, SQLException
    {

        Long l;
        String s = value.toString().trim();

        if (s.length() > 18)
        {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  Value is too long! (18 digits max)", null));
        }

        try
        {
            l = Long.parseLong(s);
            if (l > Integer.MAX_VALUE)
            {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  '" + l + "' is too large!", null));
            }
        }
        catch(NumberFormatException nfe) { l = null; }


        if (l != null)
        {

            if (ds == null) throw new SQLException("Can't get data source");

            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs;
            int cnt = 0;
            try
            {
                conn = ds.getConnection();
                ps = conn.prepareStatement("SELECT count(1) from COMPONENTSTATS where COMPONENTSTATSID = ?");
                ps.setLong(1, l);
                rs = ps.executeQuery();

                while(rs.next()) cnt = rs.getInt(1);

                if (cnt > 0)
                {
                    throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  '" + l + "' is already in use!", null));
                }

            }
            catch(SQLException x)
            {
                throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        "  SQL error!", null));
            }
            finally
            {
                if (ps != null) ps.close();
                if (conn != null) conn.close();
            }
        }
        else
        {
            throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
                        s.isEmpty() ? "  This field cannot be empty!" : "  '" + s + "' is not a number!", null));
        }

    }  

我该如何解决这个问题。

4

1 回答 1

-1

不要给出“COUNT(1)”,而是尝试给出“COUNT(*)”或“count(columnName)”。

于 2013-01-27T18:29:36.013 回答