Hi everybody,
I want to have a login form in Java, which comparing the username and password, according to MySQL database data, so I have the following code, just don't know where to add the select statement and how verify the username and password from MySQL with the JTextfield of the JAVA:

code...

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.JOptionPane;

public class Login extends JFrame implements ActionListener {
	private Container container;
	private GridBagLayout layout;
	private GridBagConstraints gbc;

	private JButton cmdLogin, cmdCancel;
	private JLabel lblUSer, lblPassword;
	private JTextField txtUser;
	private JPasswordField txtPassword;

	public Login()
	{
		
		setTitle("Login Screen"); // or  //super("Login window");
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		setResizable(false); //disable resizing and Max button

		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setSize(300,150);
		setLocationRelativeTo(null);

		container = getContentPane();
		layout = new GridBagLayout();
		container.setLayout(layout);

		gbc = new GridBagConstraints();

		lblUSer = new JLabel("Username:");
		gbc.insets = new Insets(2,2,2,2);
		container.add(lblUSer, gbc);

		txtUser = new JTextField(15);
		gbc.gridx = 1;
		gbc.gridwidth = 3;
		container.add(txtUser, gbc);

		lblPassword = new JLabel("Password:");
		gbc.gridy = 1;
		gbc.gridx = 0;
		gbc.gridwidth = 1;
		container.add(lblPassword, gbc);

		txtPassword = new JPasswordField(15);
		gbc.gridx = 1;
		gbc.gridwidth = 3;
		container.add(txtPassword, gbc);

		cmdLogin = new JButton("Login");
		cmdLogin.addActionListener( this );
		gbc.gridy = 2;
		gbc.gridx = 1;
		gbc.gridwidth = 1;
		container.add(cmdLogin, gbc);

		cmdCancel = new JButton("Cancel");
		cmdCancel.addActionListener( this );
		gbc.gridx = 2;
		container.add(cmdCancel, gbc);
	} //Login()

	public void actionPerformed(ActionEvent e){
		if(e.getActionCommand().equals("Login")){
			JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
		}
		else
		{
			//default icon, custom title
			int respond = JOptionPane.showConfirmDialog(null, "Would you like exiting the program ?", "Exiting", JOptionPane.YES_NO_OPTION);
			//System.out.println(respond);
			
			if(respond == 0){
				dispose (); //closing the frame
			}
		}
	} //actionPerformed()

	public static void connect()
	{
		Connection conn = null;

		try
		{
			String userName = "root";
			String password = "root";
			String url = "jdbc:mysql://localhost/Member";
			Class.forName ("com.mysql.jdbc.Driver").newInstance ();
			conn = DriverManager.getConnection (url, userName, password);
			System.out.println ("Database connection established");
		}
		catch (Exception e)
		{
			System.err.println ("Cannot connect to database server");
		}

		finally
		{
			if (conn != null)
			{
				try{
					conn.close ();
					System.out.println ("Database connection terminated");
				}
				catch (Exception e) 
				{
					 /* ignore close errors */ 
				}
			}
		}
	} //connect()	

	public static void main(String args[]) {
		new Login().setVisible(true);
		connect();
	} //main()

} //Login

The connection class should be declared outside the method connect() and take value inside it. In the way you have it, you create a new connection and when the connect method finishes, you can not use the conn variable since it is out of scope.
Have a method the takes as arguments username, password and then inside create the query, call the database and check if the arguments are valid. Then return true or false.
Take the username, password from the gui and call the previous method.

String s = "select username, password from table_users where username = '"+ username +
"' and password = '"+password+ "'";

Hi.
Thanks for replying and nice guide, but could you plz update the posted code, if possible plz.

If you do not understand a part of his suggestion ask for clarification, but don't expect someone to write your code for you.

public static void connect()
{
		Connection conn = null;
// the rest of your code

}

At the above method which you wrote, you correctly open a connection to the database. But the conn variable is declared inside the method locally. You cannot use it outside the method and it has no meaning, because as soon you open the connection, then you close it.
You can change the method to return the connection. Remove the code that closes the connection.
Then in another method as I said you will use the connect() method to get the connection to run the query. Then when you get the result form the query and store it in variables, close the connection and return true or false whether the user can login or not.
You will call this method where you get the username and password from the gui.

If you don't understand this then you don't know the basics of java or OOP, so don't just copy code from books (connect method) if you don't know what it does.

Hi again,
Thanks for replying and idea yeah you are right, so I changed the code, and I know the problem is about the try and catch: but I dont know how resolve this.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
import javax.swing.JOptionPane;

public class Login extends JFrame implements ActionListener {
	private Container container;
	private GridBagLayout layout;
	private GridBagConstraints gbc;

	private JButton cmdLogin, cmdCancel;
	private JLabel lblUSer, lblPassword;
	private JTextField txtUser;
	private JPasswordField txtPassword;

	String username = null;
	String password = null;

	Connection conn = null;
	Statement stat;
	PreparedStatement pstat = null;
	ResultSet rs = null;
	String dbUser = null;
	String dbPass = null;
	String dbUrl = null;
	boolean loop = false;


	public Login()
	{
		// ***************************** Connection ******************************



		try
		{
			dbUser = "root";
			dbPass = "root";
			dbUrl = "jdbc:mysql://localhost/login";
			Class.forName ("com.mysql.jdbc.Driver").newInstance ();
			conn = DriverManager.getConnection (dbUrl, dbUser, dbPass);
			System.out.println ("Database connection established");

			stat = conn.createStatement();
			System.out.println("connection opened");
				
			}
		catch (Exception e)
		{
			System.err.println ("Cannot connect to database server");
		}

		// ***************************** Connection ******************************

		setTitle("Login Screen"); // or  //super("Login window");
		setExtendedState(JFrame.MAXIMIZED_BOTH);
		setResizable(false); //disable resizing and Max button

		setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		setSize(300,150);
		setLocationRelativeTo(null);

		container = getContentPane();
		layout = new GridBagLayout();
		container.setLayout(layout);

		gbc = new GridBagConstraints();

		lblUSer = new JLabel("Username:");
		gbc.insets = new Insets(2,2,2,2);
		container.add(lblUSer, gbc);

		txtUser = new JTextField(15);
		gbc.gridx = 1;
		gbc.gridwidth = 3;
		container.add(txtUser, gbc);

		lblPassword = new JLabel("Password:");
		gbc.gridy = 1;
		gbc.gridx = 0;
		gbc.gridwidth = 1;
		container.add(lblPassword, gbc);

		txtPassword = new JPasswordField(15);
		gbc.gridx = 1;
		gbc.gridwidth = 3;
		container.add(txtPassword, gbc);

		cmdLogin = new JButton("Login");
		cmdLogin.addActionListener( this );
		gbc.gridy = 2;
		gbc.gridx = 1;
		gbc.gridwidth = 1;
		container.add(cmdLogin, gbc);

		cmdCancel = new JButton("Cancel");
		cmdCancel.addActionListener( this );
		gbc.gridx = 2;
		container.add(cmdCancel, gbc);
	} //Login()

	public void actionPerformed(ActionEvent e){
		if(e.getActionCommand().equals("Login")){

			username = new String(txtUser.getText());
			password = new String(txtPassword.getPassword());
			System.out.println("Username: " + username);
			System.out.println("Password: " + password);

			do{
				loop = false;
				pstat = conn.prepareStatement("select username,password from user where username='"+ username + "' and password = '"+password+ "'");

				pstat.setString(1,username);
				pstat.setString(2,password);
				rs = pstat.executeQuery();
				
				if(!rs.next() && rs.getRow() == 0) {
					JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
					txtUser.setText("");
					txtPassword.setText("");
					loop = true;

					break;
				}
				else{
					JOptionPane.showMessageDialog(null, "Welcome, you can use the program ...", "Welcome", JOptionPane.WARNING_MESSAGE);	
				}
			}
			while (loop);
			
				
		}
		else
		{
			//default icon, custom title
			int respond = JOptionPane.showConfirmDialog(null, "Would you like exiting the program ?", "Exiting", JOptionPane.YES_NO_OPTION);
			//System.out.println(respond);
			
			if(respond == 0){
				dispose (); //closing the frame
			}
		}
	} //actionPerformed()


	public static void main(String args[]) {
		new Login().setVisible(true);
	} //main()

} //Login

Since you are using PreparedStatement and not the simple Statement then change this:

pstat = conn.prepareStatement("select username,password from user where username='"+ username + "' and password = '"+password+ "'"); to this:

pstat = conn.prepareStatement(
"select username,password from user where username=? and password = ?"
);

After you get the resultSet and call its methods(rs.next()) and before you break, you must close everything:
rs.close();
pstat.close();
conn.close(); Note: if you want to run a query again, you must reopen the connection, so it would be better if you put the code that opens it in some method so you can call it whenever you want to open a connection

Next time besides the code, post the errors you get and at which line

Also something that I forgot:

select username,password from user where username=? and password = ?

I hope that you have a table named: user at your database, with columns: username,password

I don't know if you are going to receive this tanha, but I am going to say it anyway.
What you have tried to do is wrong from the design point of view. Even if it compiles and does exactly what you want it is not how it should be done: You cannot have you entire code with different functionalities in one method. The gui you wrote should be used to do things only a gui would do. Meaning that shouldn't implement code that connects to a database, runs the query, gets the result and then perform some actions with the result inside the actionPerformed. A better way to do this (I am not saying it is the best way but it is easier and SIMPLER) is the following: (Some details are omitted in order to reduce the code)

Have a class that only returns the connection:

class ConnectDB {
  public static Connection getConnection() {
     //code the returns the connection to the database:
    // here you write what is needed only for the connection.
   //  ... 
     conn = DriverManager.getConnection (dbUrl, dbUser, dbPass);
   //  .. ..  ...
 return conn;
  }
}

Then you have another class in which you run only the queries. One method as an example

class UserDB {
  public boolean validateUser(String user, String pass) {
    Connection conn = ConnectDB.getConnection();
    //write the query, executed, and return if the user can login or not
    return false;
  }
}

And finally you call the above inside your gui:

String user=textUser.getText();
String pass=textPass.getText();
UserDB udb=new UserDB();
boolean canLogin = udb.validateUser(user, pass);

What you gain from this:
An easy to read and maintain code. You have classes that do specific things, not one large method with everything inside. You can call them any time you want from wherever you want.
What if you wanted to go to another frame after the login and again you wanted to run a query. With your way you would have to write again the same code for opening connection and running the query and doing stuff with the results.
With my way all you have to do is call one method from the UserDB class. If you want you can put all your queries in one class or you can categorize them in classes:
In the class UserDB you could have methods for login inserting new user, updating and you can call them from wherever you want without having to write any extra code.

Now think this. what happens if the database's url changes or some other property changes. With your code you will have to go to all the places where you open the connection in order to change your code. With my way all you have to do is go to ONE class where you open the connection and you wouldn't have to change anything else.

Thanks very much for the nice feedback, and solution.
I went through the code and everything seems fine, but I don't know I enter the correct username and password, but still I see the message of the Wrong password or Username?

Here is the code I did as you mentioned:

//ConnectDB.java

import com.mysql.jdbc.Connection;
import java.sql.DriverManager;

class ConnectDB {
    private static Connection cn;
    public void ConnectDB(){
        
    }
    
    public static Connection getConnection() {
        
    //code the returns the connection to the database:
    // here you write what is needed only for the connection.
    //  ... 

        try {
            Class.forName("com.mysql.jdbc.Driver").newInstance();
            cn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/dictionary?"+ "user=root&password=root");

        } 
        catch (Exception ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
        }
        return cn;
}
}

=============

//UserDB.java

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;

class UserDB {
    Statement stat;
    PreparedStatement pstat = null;
    ResultSet rs = null;
    boolean result;
        
    public UserDB(){
        
    }
    
    public boolean validateUser(String username, String password) {
        Connection conn = ConnectDB.getConnection();
        
        //write the query, executed, and return if the user can login or not
        try {
            pstat = conn.prepareStatement("select username,password from user where username='"+ username + "' and password = '"+password+ "'");

            pstat.setString(1,username);
            pstat.setString(2,password);
            rs = pstat.executeQuery();

            if(!rs.next() && rs.getRow() == 0) {
                result = false;
            }
            else{
                result = true;   
            }
        }
        catch (Exception ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
        }
        return result;
    }
}

============

//LoginForm.java

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class LoginForm extends JFrame {

    // Variables declaration
        private JLabel jLabel1;
        private JLabel jLabel2;
        private JTextField jTextField1;
        private JPasswordField jPasswordField1;
        private JButton jButton1;
        private JPanel contentPane;
        boolean loop = false;
    // End of variables declaration

    public LoginForm() {
        super();
        create();
        this.setVisible(true);
    }

    private void create() {         
        jLabel1 = new JLabel();
        jLabel2 = new JLabel();
        jTextField1 = new JTextField();
        jPasswordField1 = new JPasswordField();
        jButton1 = new JButton();
        contentPane = (JPanel)this.getContentPane();

        //
        // jLabel1
        //
            jLabel1.setHorizontalAlignment(SwingConstants.LEFT);
            jLabel1.setForeground(new Color(0, 0, 255));
            jLabel1.setText("username:");
        //
        // jLabel2
        //
            jLabel2.setHorizontalAlignment(SwingConstants.LEFT);
            jLabel2.setForeground(new Color(0, 0, 255));
            jLabel2.setText("password:");
        //
        // jTextField1
        //
            jTextField1.setForeground(new Color(0, 0, 255));
            jTextField1.setSelectedTextColor(new Color(0, 0, 255));
            jTextField1.setToolTipText("Enter your username");

        //
        // jPasswordField1
        //
            jPasswordField1.setForeground(new Color(0, 0, 255));
            jPasswordField1.setToolTipText("Enter your password");

        //
        // jButton1
        //
            jButton1.setBackground(new Color(204, 204, 204));
            jButton1.setForeground(new Color(0, 0, 255));
            jButton1.setText("Login");
            jButton1.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    jButton1_actionPerformed(e);
                }

            });
            
        //
        // contentPane
        //
            contentPane.setLayout(null);
            contentPane.setBorder(BorderFactory.createEtchedBorder());
            contentPane.setBackground(new Color(204, 204, 204));
            addComponent(contentPane, jLabel1, 5,10,106,18);
            addComponent(contentPane, jLabel2, 5,47,97,18);
            addComponent(contentPane, jTextField1, 110,10,183,22);
            addComponent(contentPane, jPasswordField1, 110,45,183,22);
            addComponent(contentPane, jButton1, 150,75,83,28);

        //
        // login
        //
            this.setTitle("Login To Members Area");
            this.setLocation(new Point(76, 182));
            this.setSize(new Dimension(335, 141));
            this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            this.setResizable(false);
    } //end of create()

    /** Add Component Without a Layout Manager (Absolute Positioning) */
    private void addComponent(Container container,Component c,int x,int y,int width,int height) {
        c.setBounds(x,y,width,height);
        container.add(c);
    } //end of addComponent()

    private void jButton1_actionPerformed(ActionEvent e) {
        
        String username = new String(jTextField1.getText());
        String password = new String(jPasswordField1.getText());

        if(username.equals("") || password.equals("")) { // If password and username is empty > Do this >>>
        
            jButton1.setEnabled(false);
            JLabel errorFields = new JLabel("<HTML><FONT COLOR = Blue>You must enter a username and password to login.</FONT></HTML>");	
            JOptionPane.showMessageDialog(null,errorFields); 
            jTextField1.setText("");
            jPasswordField1.setText("");
            jButton1.setEnabled(true);
            this.setVisible(true);
        } //end of if
        else {

            UserDB udb=new UserDB();
            boolean canLogin = udb.validateUser(username, password);

            do{
                loop = false;

                if(!canLogin) {
                    JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
                    jTextField1.setText("");
                    jPasswordField1.setText("");
                    loop = true;
                    break;
                } //end of if
                else {
                    JOptionPane.showMessageDialog(null, "Welcome, you can use the program ...", "Welcome", JOptionPane.WARNING_MESSAGE);	
                } //end of else
            } //end of do
            while (loop); 
        } //end of else  
    } //end of jButton1_actionPerformed()  

    public static void main(String[] args) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        JDialog.setDefaultLookAndFeelDecorated(true);

        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } //end of try
        
        catch (Exception ex) {
            System.out.println("Failed loading L&F: ");
            System.out.println(ex);
        } //end of catch
        
        new LoginForm();
    }; //end of main()

} //end of LoginForm

can you please have another look ?
regards,

Read this post

Since you are using PreparedStatement and not the simple Statement then change this:

pstat = conn.prepareStatement("select username,password from user where username='"+ username + "' and password = '"+password+ "'"); to this:

pstat = conn.prepareStatement(
"select username,password from user where username=? and password = ?"
);

Your real problem is this:

public boolean validateUser(String username, String password) {
        Connection conn = ConnectDB.getConnection();
        
        //write the query, executed, and return if the user can login or not
        try {
            pstat = conn.prepareStatement("select username,password from user where username='"+ username + "' and password = '"+password+ "'");

            pstat.setString(1,username);
            pstat.setString(2,password);
            rs = pstat.executeQuery();

            if(!rs.next() && rs.getRow() == 0) {
                result = false;
            }
            else{
                result = true;   
            }
        }
        catch (Exception ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
        }
        return result;
    }
}

You catch the exception but you return the result (true or false) like nothing happened. You need to indicate to the one who called the method that something went wrong. If you simple print the error and then return the user will think that the password was wrong even though you had an exception. Try this:

public boolean validateUser(String username, String password) throws Exception {
        Connection conn = ConnectDB.getConnection();
        
        //write the query, executed, and return if the user can login or not
        try {
            
        }
        catch (Exception ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            throw ex;
        }
        return result;
    }
}

And now this:

do{
                loop = false;

                if(!canLogin) {
                    JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
                    jTextField1.setText("");
                    jPasswordField1.setText("");
                    loop = true;
                    break;
                } //end of if
                else {
                    JOptionPane.showMessageDialog(null, "Welcome, you can use the program ...", "Welcome", JOptionPane.WARNING_MESSAGE);	
                } //end of else
            } //end of do
            while (loop);

If the login is wrong you set the loop=true meaning that you will repeat the while-loop but then you break, so the loop=true is meaningless, as well as the while-loop
If the login is correct you print the message and you continue (without resetting the loop=false). Again the while-loop is meaningless.

What exactly you want to do?

Another mistake that you made, hence the third different post so you will not confuse them is that you don't close the ResultSet, the pstm and the conn.

public boolean validateUser(String username, String password) {
        Connection conn = ConnectDB.getConnection();
        
        //write the query, executed, and return if the user can login or not
        try {
            pstat = conn.prepareStatement("select username,password from user 
where username= ? and password = ?");

            pstat.setString(1,username);
            pstat.setString(2,password);
            rs = pstat.executeQuery();

            if(!rs.next() && rs.getRow() == 0) {
                result = false;
            }
            else{
                result = true;   
            }
        }
        catch (Exception ex) {
            // handle any errors
            System.out.println("SQLException: " + ex.getMessage());
            throw ex;
        } finally {
             if (rs!=null) rs.close();
            if (pstat!=null) pstat.close();
           if (conn !=null) conn.close();
        }
        return result;
    }
}

Thanks again for guiding, and also thanks for mentioning about the loop, for the moment it is useless, I will use it just, if the user enter wrong username and password more than three times, then the project exists.

follow JavaAddict instruction:

try this: erase the statement loop=true then thats it. it works for me.

regards JavaAddict:)))

do{
                loop = false;

                if(!canLogin) {
                    JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
                    tf.setText("");
                    pf.setText("");
                   //loop = true;
                    break;
                } //end of if
                else {
                    JOptionPane.showMessageDialog(null, "Welcome, you can use the program ...", "Welcome", JOptionPane.WARNING_MESSAGE);
                } //end of else
            } //end of do
            while (loop);
        } //end of else

Edited 3 Years Ago by Reverend Jim: Fixed formatting

Comments
Unnecessarily reviving an old thread

Thank you for repeating my code. I am sure that after months tanha hasn't solved his problem, but you were the one he was waiting for.

Thanks dear for the replying ...

Thanks from all, sorry posting too late

This article has been dead for over six months. Start a new discussion instead.