Java SQL唯一用户名

时间:2014-01-26 13:52:09

标签: java mysql database

空白数据库。

如果我输入用户名example1,它将添加到数据库中。然后,如果我再次尝试重新添加它,它将被我的代码停止,因为它已经在数据库中。然后,如果我输入example2并添加它将进入数据库,然后如果我尝试重新添加它,我的代码让它通过唯一阻止它的是数据库主键:

我认为这一行是个问题:

        PreparedStatement st = connection.prepareStatement("select * from Members order by username asc");

以下是整个方法:

public static boolean CheckUsernameExists(String username){

    boolean usernameExists = false;

    try{
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection(urlDB, usernameDB, passwordDB);

        PreparedStatement st = connection.prepareStatement("select * from Members order by username asc");
        ResultSet r1=st.executeQuery();
        String usernameCounter;
        if(r1.next()){
            usernameCounter =  r1.getString("username");
            if(usernameCounter.equals(username)){
                System.out.println(username);
                usernameExists = true;
            }
        }
     } catch (SQLException e) {
        System.out.println("SQL Exception: "+ e.toString());
     }catch (ClassNotFoundException cE){
        System.out.println("Class Not Found Exception: "+ cE.toString());
     }

    return usernameExists;
}

4 个答案:

答案 0 :(得分:4)

应该更好:

    PreparedStatement st = connection.prepareStatement("select * from Members where username = ? ");
    st.setString(1, username);
    ResultSet r1=st.executeQuery();
    if(r1.next()){
         System.out.println('user already exist in database!");
    }
    else{
        //Add to database
    }

或者因为您的方法是CheckUsernameExists

public static boolean CheckUsernameExists(String username){

    boolean usernameExists = false;
    try{
        PreparedStatement st = connection.prepareStatement("select * from Members where username = ? ");
        st.setString(1, username);
        ResultSet r1=st.executeQuery();
        if(r1.next()){
           usernameExists = true;
        }
    catch (Exception e) {
        System.out.println("SQL Exception: "+ e.toString());
    }
    return usernameExists;
}

答案 1 :(得分:1)

不要遍历所有用户。只需尝试从数据库中选择所需的用户名。此外,如果您使用提供的字符串,您将面临SQL注入的危险。试试并使用它:

PreparedStatement st = connection.prepareStatement("select * from Members where username = ?");
st.setString(1, username);
ResultSet rs = st.executeQuery();

答案 2 :(得分:0)

使用此功能可以实现您想要的效果:

PreparedStatement st = connection.prepareStatement("select id from Members where username = ? ");
    //I assumed that their is id column in Members.
    st.setString(1, username);
    ResultSet resultSet=st.executeQuery();
    if(resultSet.next()){
         // prompt users already exists
    }
    else{
        //add to database
    }

只需获取一个代表给定行的列,它实际上无关紧要因为您只检查是否有一行具有用户指定的用户名。 (根据您当前的规格而定)。

答案 3 :(得分:-1)

将您的查询更改为以下内容:

"select * from Members where username=" +  username

它只会返回给您这个用户,没有必要从数据库中请求所有用户,然后在应用程序上过滤它们。您重载应用程序和数据库。