•
•
•
•
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
![]() |
•
•
Join Date: Aug 2007
Posts: 141
Reputation:
Rep Power: 0
Solved Threads: 0
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...
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+ "'";
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
public static void connect()
{
Connection conn = null;
// the rest of your code
}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
•
•
Join Date: Aug 2007
Posts: 141
Reputation:
Rep Power: 0
Solved Threads: 0
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.
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
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
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:
Then you have another class in which you run only the queries. One method as an example
And finally you call the above inside your gui:
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.
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;
}
}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
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb Java Marketplace
- Previous Thread: project for stand alone system jwellary shop ?
- Next Thread: Full path of a running process using java?



Linear Mode