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 422,390 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 4,809 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: 1521 | Replies: 14
Reply
Join Date: Aug 2007
Posts: 167
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: 167
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: 537
Reputation: javaAddict will become famous soon enough javaAddict will become famous soon enough 
Rep Power: 3
Solved Threads: 57
javaAddict's Avatar
javaAddict javaAddict is online now Online
Posting Pro

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: 167
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,813
Reputation: Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all Ezzaral is a name known to all 
Rep Power: 12
Solved Threads: 281
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: 537
Reputation: javaAddict will become famous soon enough javaAddict will become famous soon enough 
Rep Power: 3
Solved Threads: 57
javaAddict's Avatar
javaAddict javaAddict is online now Online
Posting Pro

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: 167
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: 537
Reputation: javaAddict will become famous soon enough javaAddict will become famous soon enough 
Rep Power: 3
Solved Threads: 57
javaAddict's Avatar
javaAddict javaAddict is online now Online
Posting Pro

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: 537
Reputation: javaAddict will become famous soon enough javaAddict will become famous soon enough 
Rep Power: 3
Solved Threads: 57
javaAddict's Avatar
javaAddict javaAddict is online now Online
Posting Pro

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: 537
Reputation: javaAddict will become famous soon enough javaAddict will become famous soon enough 
Rep Power: 3
Solved Threads: 57
javaAddict's Avatar
javaAddict javaAddict is online now Online
Posting Pro

Re: Login Form verification MySQL "Java"

  #10  
20 Days Ago
Read this post

Originally Posted by javaAddict View 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 = ?"
);

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.

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

 

Thread Tools Display Modes

Other Threads in the Java Forum

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