| | |
Login Form verification MySQL "Java"
![]() |
•
•
Join Date: Aug 2007
Posts: 199
Reputation:
Solved Threads: 0
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:
=============
============
can you please have another look ?
regards,
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:
Java Syntax (Toggle Plain Text)
//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; } }
=============
Java Syntax (Toggle Plain Text)
//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; } }
============
Java Syntax (Toggle Plain Text)
//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 = ?"
);
Check out my New Bike at my Public Profile at the "About Me" tab
Your real problem is this:
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:
And now this:
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?
Java Syntax (Toggle Plain Text)
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:
Java Syntax (Toggle Plain Text)
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:
Java Syntax (Toggle Plain Text)
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?
Check out my New Bike at my Public Profile at the "About Me" tab
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.
Java Syntax (Toggle Plain Text)
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; } }
Last edited by javaAddict; Sep 15th, 2008 at 5:12 pm.
Check out my New Bike at my Public Profile at the "About Me" tab
•
•
Join Date: Jul 2008
Posts: 18
Reputation:
Solved Threads: 0
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
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
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.
Check out my New Bike at my Public Profile at the "About Me" tab
It would be good idea if you share solution, if you got one, and finally close this thread...
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
![]() |
Other Threads in the Java Forum
- Previous Thread: Need Suggestion (Java/SQL)
- Next Thread: How do i fix this??URGENT!!
| Thread Tools | Search this Thread |
-xlint actionlistener android api applet application array arrays automation bi binary blackberry block bluetooth character chat class client code compile compiler component consumer database desktop developmenthelp eclipse error fractal freeze ftp game gameprogramming givemetehcodez graphics gui html ide image integer j2me j2seprojects java javac javaee javaprojects jetbrains jni jpanel jtable julia learningresources lego linked linux list loops mac map method methods mobile netbeans newbie notdisplaying number online printf problem program programming project properties qt recursion researchinmotion rotatetext rsa scanner screen server set singleton sms sort sql string swing system textfields threads time title tree tutorial-sample update variablebinding windows working xor






