User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Java section within the Software Development category of DaniWeb, a massive community of 375,198 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,036 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Java advertiser: Lunarpages Java Web Hosting
Views: 835 | Replies: 9
Reply
Join Date: Aug 2007
Posts: 141
Reputation: tanha is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Login Form verification MySQL "Java"

  #1  
Apr 17th, 2008
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
AddThis Social Bookmark Button
Reply With Quote  
Join Date: Aug 2007
Posts: 141
Reputation: tanha is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Re: Login Form verification MySQL "Java"

  #2  
Apr 18th, 2008
Hi.
anyone help here
Reply With Quote  
Join Date: Dec 2007
Location: Greece
Posts: 385
Reputation: javaAddict is on a distinguished road 
Rep Power: 1
Solved Threads: 35
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Whiz

Re: Login Form verification MySQL "Java"

  #3  
Apr 18th, 2008
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+ "'";
I AM the 12th CYLON
Reply With Quote  
Join Date: Aug 2007
Posts: 141
Reputation: tanha is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Re: Login Form verification MySQL "Java"

  #4  
Apr 18th, 2008
Hi.
Thanks for replying and nice guide, but could you plz update the posted code, if possible plz.
Reply With Quote  
Join Date: May 2007
Location: USA
Posts: 2,504
Reputation: Ezzaral is just really nice Ezzaral is just really nice Ezzaral is just really nice Ezzaral is just really nice 
Rep Power: 10
Solved Threads: 252
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is offline Offline
Posting Maven

Re: Login Form verification MySQL "Java"

  #5  
Apr 18th, 2008
If you do not understand a part of his suggestion ask for clarification, but don't expect someone to write your code for you.
Reply With Quote  
Join Date: Dec 2007
Location: Greece
Posts: 385
Reputation: javaAddict is on a distinguished road 
Rep Power: 1
Solved Threads: 35
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Whiz

Re: Login Form verification MySQL "Java"

  #6  
Apr 18th, 2008
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.
I AM the 12th CYLON
Reply With Quote  
Join Date: Aug 2007
Posts: 141
Reputation: tanha is an unknown quantity at this point 
Rep Power: 0
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Re: Login Form verification MySQL "Java"

  #7  
Apr 18th, 2008
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
Reply With Quote  
Join Date: Dec 2007
Location: Greece
Posts: 385
Reputation: javaAddict is on a distinguished road 
Rep Power: 1
Solved Threads: 35
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Whiz

Re: Login Form verification MySQL "Java"

  #8  
Apr 19th, 2008
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
I AM the 12th CYLON
Reply With Quote  
Join Date: Dec 2007
Location: Greece
Posts: 385
Reputation: javaAddict is on a distinguished road 
Rep Power: 1
Solved Threads: 35
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Whiz

Re: Login Form verification MySQL "Java"

  #9  
Apr 19th, 2008
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 AM the 12th CYLON
Reply With Quote  
Join Date: Dec 2007
Location: Greece
Posts: 385
Reputation: javaAddict is on a distinguished road 
Rep Power: 1
Solved Threads: 35
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Whiz

Re: Login Form verification MySQL "Java"

  #10  
Apr 22nd, 2008
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.
Last edited by javaAddict : Apr 22nd, 2008 at 7:25 am.
I AM the 12th CYLON
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb Java Marketplace
Thread Tools Display Modes

Other Threads in the Java Forum

All times are GMT -4. The time now is 2:19 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC