0

So I have this working code/prepared statement that adds a username and password into a database, however I need to check if the username already exists in the code.

public void addUser(Connection conn, PreparedStatement pstmnt, String username, String password) 
    {
        try 
        {
            pstmnt = conn.prepareStatement("insert into users values (?,?,?)");
            pstmnt.setInt(1, 0);
            pstmnt.setString(2, username);
            pstmnt.setString(3, password);
            pstmnt.executeUpdate();
        } 
        catch (SQLException e) { System.out.println("Error: " + e.getMessage()); }

        System.out.println(username + " has been added");
    }

Is there any simple way to do this?

2
  • 1
    Using a unique constraint in the database does not work? Commented Jun 18, 2013 at 13:08
  • What @UwePlonus says -- just enforce the constraint at the database level. This is what a primary key is. Commented Jun 18, 2013 at 13:29

2 Answers 2

1

You can add a unique constraint in the DB and handle the exception in addUSer accordingly

Sign up to request clarification or add additional context in comments.

1 Comment

+1, that is the best solution. For example with the statement ALTER TABLE users ADD CONSTRAINT users_uq_name UNIQUE (username);
0

If there's no many duplicate key risk, you can just try and check the error code if it matches "dup key error" (Error ORA-00001).

Else you must lock the entire table, check for key existence, update and then commit (which release the lock)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.