Java:检查自动生成的ID

时间:2011-05-24 18:46:15

标签: java sql unique

我的Java程序将项目添加到数据库中。我有一个代码,用于生成将用作项ID的随机字符串。我想制作IDchecker(id)来检查ID是否已经存在于数据库中。

如果我有codeIDgenerator()和IDchecker(id)方法,如何在ID已经存在的情况下创建一个将生成新代码的循环,或者如果ID是唯一的并且没有出现,则将退出循环数据库?

我的IDchecker(id)方法也遇到了问题,我正在使用ResultSet从SQL中恢复数据,但我找不到确定ResultSet有多少行的方法(如果有的话) )。 resultSet没有isEmpty()?

以下是代码:

public void AddItem() {
    boolean checkCode = false;
    while (checkCode == false) {
        Random r = new Random();
        int numbers = 100000 + (int) (r.nextFloat() * 899900);
        String ID= Integer.toString(numbers);
        try {
            if (DatabaseConnection.checkID(ID) == false) {
                checkCode = true;
                System.out.println("ID is unique");
            } else if (DatabaseConnection.checkID(ID) == true) {
                System.out.println("ID is NOT unique");
            }
        } catch (SQLException ex) {
            Logger.getLogger(ModelTabeleIntervencija.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

这是ckeckID(ID)方法

public boolean CheckID(String ID) throws SQLException {
    String query = "SELECT itemId FROM items WHERE itemID= '"+ID+"'";
    Statement dbStatement = connection.createStatement();
    ResultSet rsItems= dbStatement .executeQuery(query);
        if (rsItems.isEmpty( )== true){
            return false;
            // ID not found - is unique
        } else{
        return true;
            // ID found - is not unique
        }
}

由于

1 个答案:

答案 0 :(得分:0)

虽然最好在数据库中生成唯一ID,但我可以帮助您简化代码。您不需要两次检查数据库。

private final Random r = new Random();
public String getUniqueId() {
    try {
        while (true) {
            int n = r.nextInt(1000 * 1000) + 1000 * 1000;
            String id = ("" + n).substring(1); // number between 000000 and 999999
            if (DatabaseConnection.checkID(id))
                return id;
        }
    } catch (SQLException ex) {
        throw new IllegalStateException("Cannot access database", ex);
    }
}

但是,您可以只获取下一个ID,而不是生成随机ID。

public String getUniqueId() {
    try {
        String maxId = DatabaseConnection.selectMaxId();
        int n = Integer.parseInt(maxId) + 1;
        return ("" + n).substring(1); // number between 000000 and 999999
    } catch (SQLException ex) {
        throw new IllegalStateException("Cannot access database", ex);
    }
}