Abolarin Anuoluwapo
Abolarin Anuoluwapo

Reputation: 11

how to check if a mysql user exists in java

I have a code that registers users in mySql and I want it to be able to check if the user already exists before creating it

This is what i have currently

@EJB
private UserEJB userEJB;

private User user;


protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
    // TODO Auto-generated method stub
        String firstname = request.getParameter("fname");
        String surname = request.getParameter("sname");
        String email = request.getParameter("email");
        String password = request.getParameter("password");

        user = new User(firstname, surname, email, password);
        CreateUser(user);
        JOptionPane.showMessageDialog(null, "Thank You for Registering, Login to continue");
        RequestDispatcher rsd = request.getRequestDispatcher("login.html");
        rsd.forward(request, response);
    }
}


public void CreateUser(User user){
       userEJB.addUser(user);
}

Upvotes: 1

Views: 658

Answers (1)

Hasitha Jayawardana
Hasitha Jayawardana

Reputation: 2426

You didn't post more information. So I will give you a basic idea to achieve what you need.

I will get email as a unique field because the same email address can't be there for two users. So your SQL query should be something like this.

SELECT * FROM users WHERE email = ? // Select all users belongs to the provided email

And a example code for your reference,

    boolean isAvailable = false;
    String email = request.getParameter("email"); // Get email from a form

    String query = "SELECT * FROM users WHERE email = ?"; // Select all users belongs to the provided email

    try {
            PreparedStatement statement; // Using a preparedStatement to prevent SQL-Injection
            ResultSet resultSet;
            statement = connection.prepareStatement(query);
            statement.setString(1, email);
            resultSet = statement.executeQuery();

            if(resultSet.next()) {
                isAvailable = true;
            } else {
                isAvailable = false;
            }
    } catch (SQLException ex) {
         ex.printStackTrace();
    }

So if isAvailable gives true the user is already a registered user in your case. But if isAvailable gives false the user is not in the database.

Hope this helps you.

Upvotes: 1

Related Questions