简体   繁体   中英

Checking if user exists in Oracle Database - java jdbc

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?

您可以在数据库中添加唯一约束,并相应地在addUSer中处理异常

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM