Login Form verification MySQL "Java"

Reply

Join Date: Aug 2007
Posts: 199
Reputation: tanha is an unknown quantity at this point 
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Login Form verification MySQL "Java"

 
0
  #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...
  1.  
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. import java.sql.*;
  6. import javax.swing.JOptionPane;
  7.  
  8. public class Login extends JFrame implements ActionListener {
  9. private Container container;
  10. private GridBagLayout layout;
  11. private GridBagConstraints gbc;
  12.  
  13. private JButton cmdLogin, cmdCancel;
  14. private JLabel lblUSer, lblPassword;
  15. private JTextField txtUser;
  16. private JPasswordField txtPassword;
  17.  
  18. public Login()
  19. {
  20.  
  21. setTitle("Login Screen"); // or //super("Login window");
  22. setExtendedState(JFrame.MAXIMIZED_BOTH);
  23. setResizable(false); //disable resizing and Max button
  24.  
  25. setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  26. setSize(300,150);
  27. setLocationRelativeTo(null);
  28.  
  29. container = getContentPane();
  30. layout = new GridBagLayout();
  31. container.setLayout(layout);
  32.  
  33. gbc = new GridBagConstraints();
  34.  
  35. lblUSer = new JLabel("Username:");
  36. gbc.insets = new Insets(2,2,2,2);
  37. container.add(lblUSer, gbc);
  38.  
  39. txtUser = new JTextField(15);
  40. gbc.gridx = 1;
  41. gbc.gridwidth = 3;
  42. container.add(txtUser, gbc);
  43.  
  44. lblPassword = new JLabel("Password:");
  45. gbc.gridy = 1;
  46. gbc.gridx = 0;
  47. gbc.gridwidth = 1;
  48. container.add(lblPassword, gbc);
  49.  
  50. txtPassword = new JPasswordField(15);
  51. gbc.gridx = 1;
  52. gbc.gridwidth = 3;
  53. container.add(txtPassword, gbc);
  54.  
  55. cmdLogin = new JButton("Login");
  56. cmdLogin.addActionListener( this );
  57. gbc.gridy = 2;
  58. gbc.gridx = 1;
  59. gbc.gridwidth = 1;
  60. container.add(cmdLogin, gbc);
  61.  
  62. cmdCancel = new JButton("Cancel");
  63. cmdCancel.addActionListener( this );
  64. gbc.gridx = 2;
  65. container.add(cmdCancel, gbc);
  66. } //Login()
  67.  
  68. public void actionPerformed(ActionEvent e){
  69. if(e.getActionCommand().equals("Login")){
  70. JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
  71. }
  72. else
  73. {
  74. //default icon, custom title
  75. int respond = JOptionPane.showConfirmDialog(null, "Would you like exiting the program ?", "Exiting", JOptionPane.YES_NO_OPTION);
  76. //System.out.println(respond);
  77.  
  78. if(respond == 0){
  79. dispose (); //closing the frame
  80. }
  81. }
  82. } //actionPerformed()
  83.  
  84. public static void connect()
  85. {
  86. Connection conn = null;
  87.  
  88. try
  89. {
  90. String userName = "root";
  91. String password = "root";
  92. String url = "jdbc:mysql://localhost/Member";
  93. Class.forName ("com.mysql.jdbc.Driver").newInstance ();
  94. conn = DriverManager.getConnection (url, userName, password);
  95. System.out.println ("Database connection established");
  96. }
  97. catch (Exception e)
  98. {
  99. System.err.println ("Cannot connect to database server");
  100. }
  101.  
  102. finally
  103. {
  104. if (conn != null)
  105. {
  106. try{
  107. conn.close ();
  108. System.out.println ("Database connection terminated");
  109. }
  110. catch (Exception e)
  111. {
  112. /* ignore close errors */
  113. }
  114. }
  115. }
  116. } //connect()
  117.  
  118. public static void main(String args[]) {
  119. new Login().setVisible(true);
  120. connect();
  121. } //main()
  122.  
  123. } //Login
Reply With Quote Quick reply to this message  
Join Date: Aug 2007
Posts: 199
Reputation: tanha is an unknown quantity at this point 
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Re: Login Form verification MySQL "Java"

 
0
  #2
Apr 18th, 2008
Hi.
anyone help here
Reply With Quote Quick reply to this message  
Join Date: Dec 2007
Posts: 1,653
Reputation: javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all 
Solved Threads: 223
Featured Poster
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Virtuoso

Re: Login Form verification MySQL "Java"

 
0
  #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+ "'";
Check out my New Bike at my Public Profile at the "About Me" tab
Reply With Quote Quick reply to this message  
Join Date: Aug 2007
Posts: 199
Reputation: tanha is an unknown quantity at this point 
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Re: Login Form verification MySQL "Java"

 
0
  #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 Quick reply to this message  
Join Date: May 2007
Posts: 4,438
Reputation: Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of Ezzaral has much to be proud of 
Solved Threads: 510
Moderator
Featured Poster
Ezzaral's Avatar
Ezzaral Ezzaral is offline Offline
Industrious Poster

Re: Login Form verification MySQL "Java"

 
0
  #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 Quick reply to this message  
Join Date: Dec 2007
Posts: 1,653
Reputation: javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all 
Solved Threads: 223
Featured Poster
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Virtuoso

Re: Login Form verification MySQL "Java"

 
0
  #6
Apr 18th, 2008
  1. public static void connect()
  2. {
  3. Connection conn = null;
  4. // the rest of your code
  5.  
  6. }
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.
Check out my New Bike at my Public Profile at the "About Me" tab
Reply With Quote Quick reply to this message  
Join Date: Aug 2007
Posts: 199
Reputation: tanha is an unknown quantity at this point 
Solved Threads: 0
tanha tanha is offline Offline
Junior Poster

Re: Login Form verification MySQL "Java"

 
0
  #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.

  1.  
  2. import java.awt.*;
  3. import java.awt.event.*;
  4. import javax.swing.*;
  5. import java.sql.*;
  6. import javax.swing.JOptionPane;
  7.  
  8. public class Login extends JFrame implements ActionListener {
  9. private Container container;
  10. private GridBagLayout layout;
  11. private GridBagConstraints gbc;
  12.  
  13. private JButton cmdLogin, cmdCancel;
  14. private JLabel lblUSer, lblPassword;
  15. private JTextField txtUser;
  16. private JPasswordField txtPassword;
  17.  
  18. String username = null;
  19. String password = null;
  20.  
  21. Connection conn = null;
  22. Statement stat;
  23. PreparedStatement pstat = null;
  24. ResultSet rs = null;
  25. String dbUser = null;
  26. String dbPass = null;
  27. String dbUrl = null;
  28. boolean loop = false;
  29.  
  30.  
  31. public Login()
  32. {
  33. // ***************************** Connection ******************************
  34.  
  35.  
  36.  
  37. try
  38. {
  39. dbUser = "root";
  40. dbPass = "root";
  41. dbUrl = "jdbc:mysql://localhost/login";
  42. Class.forName ("com.mysql.jdbc.Driver").newInstance ();
  43. conn = DriverManager.getConnection (dbUrl, dbUser, dbPass);
  44. System.out.println ("Database connection established");
  45.  
  46. stat = conn.createStatement();
  47. System.out.println("connection opened");
  48.  
  49. }
  50. catch (Exception e)
  51. {
  52. System.err.println ("Cannot connect to database server");
  53. }
  54.  
  55. // ***************************** Connection ******************************
  56.  
  57. setTitle("Login Screen"); // or //super("Login window");
  58. setExtendedState(JFrame.MAXIMIZED_BOTH);
  59. setResizable(false); //disable resizing and Max button
  60.  
  61. setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
  62. setSize(300,150);
  63. setLocationRelativeTo(null);
  64.  
  65. container = getContentPane();
  66. layout = new GridBagLayout();
  67. container.setLayout(layout);
  68.  
  69. gbc = new GridBagConstraints();
  70.  
  71. lblUSer = new JLabel("Username:");
  72. gbc.insets = new Insets(2,2,2,2);
  73. container.add(lblUSer, gbc);
  74.  
  75. txtUser = new JTextField(15);
  76. gbc.gridx = 1;
  77. gbc.gridwidth = 3;
  78. container.add(txtUser, gbc);
  79.  
  80. lblPassword = new JLabel("Password:");
  81. gbc.gridy = 1;
  82. gbc.gridx = 0;
  83. gbc.gridwidth = 1;
  84. container.add(lblPassword, gbc);
  85.  
  86. txtPassword = new JPasswordField(15);
  87. gbc.gridx = 1;
  88. gbc.gridwidth = 3;
  89. container.add(txtPassword, gbc);
  90.  
  91. cmdLogin = new JButton("Login");
  92. cmdLogin.addActionListener( this );
  93. gbc.gridy = 2;
  94. gbc.gridx = 1;
  95. gbc.gridwidth = 1;
  96. container.add(cmdLogin, gbc);
  97.  
  98. cmdCancel = new JButton("Cancel");
  99. cmdCancel.addActionListener( this );
  100. gbc.gridx = 2;
  101. container.add(cmdCancel, gbc);
  102. } //Login()
  103.  
  104. public void actionPerformed(ActionEvent e){
  105. if(e.getActionCommand().equals("Login")){
  106.  
  107. username = new String(txtUser.getText());
  108. password = new String(txtPassword.getPassword());
  109. System.out.println("Username: " + username);
  110. System.out.println("Password: " + password);
  111.  
  112. do{
  113. loop = false;
  114. pstat = conn.prepareStatement("select username,password from user where username='"+ username + "' and password = '"+password+ "'");
  115.  
  116. pstat.setString(1,username);
  117. pstat.setString(2,password);
  118. rs = pstat.executeQuery();
  119.  
  120. if(!rs.next() && rs.getRow() == 0) {
  121. JOptionPane.showMessageDialog(null, "Wrong Username or Password, try again", "Warning !!!", JOptionPane.WARNING_MESSAGE);
  122. txtUser.setText("");
  123. txtPassword.setText("");
  124. loop = true;
  125.  
  126. break;
  127. }
  128. else{
  129. JOptionPane.showMessageDialog(null, "Welcome, you can use the program ...", "Welcome", JOptionPane.WARNING_MESSAGE);
  130. }
  131. }
  132. while (loop);
  133.  
  134.  
  135. }
  136. else
  137. {
  138. //default icon, custom title
  139. int respond = JOptionPane.showConfirmDialog(null, "Would you like exiting the program ?", "Exiting", JOptionPane.YES_NO_OPTION);
  140. //System.out.println(respond);
  141.  
  142. if(respond == 0){
  143. dispose (); //closing the frame
  144. }
  145. }
  146. } //actionPerformed()
  147.  
  148.  
  149. public static void main(String args[]) {
  150. new Login().setVisible(true);
  151. } //main()
  152.  
  153. } //Login
Reply With Quote Quick reply to this message  
Join Date: Dec 2007
Posts: 1,653
Reputation: javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all 
Solved Threads: 223
Featured Poster
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Virtuoso

Re: Login Form verification MySQL "Java"

 
0
  #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
Check out my New Bike at my Public Profile at the "About Me" tab
Reply With Quote Quick reply to this message  
Join Date: Dec 2007
Posts: 1,653
Reputation: javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all 
Solved Threads: 223
Featured Poster
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Virtuoso

Re: Login Form verification MySQL "Java"

 
0
  #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
Check out my New Bike at my Public Profile at the "About Me" tab
Reply With Quote Quick reply to this message  
Join Date: Dec 2007
Posts: 1,653
Reputation: javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all javaAddict is a name known to all 
Solved Threads: 223
Featured Poster
javaAddict's Avatar
javaAddict javaAddict is offline Offline
Posting Virtuoso

Re: Login Form verification MySQL "Java"

 
0
  #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:
  1. class ConnectDB {
  2. public static Connection getConnection() {
  3. //code the returns the connection to the database:
  4. // here you write what is needed only for the connection.
  5. // ...
  6. conn = DriverManager.getConnection (dbUrl, dbUser, dbPass);
  7. // .. .. ...
  8. return conn;
  9. }
  10. }
Then you have another class in which you run only the queries. One method as an example
  1. class UserDB {
  2. public boolean validateUser(String user, String pass) {
  3. Connection conn = ConnectDB.getConnection();
  4. //write the query, executed, and return if the user can login or not
  5. return false;
  6. }
  7. }
And finally you call the above inside your gui:
  1. String user=textUser.getText();
  2. String pass=textPass.getText();
  3. UserDB udb=new UserDB();
  4. 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 8:25 am.
Check out my New Bike at my Public Profile at the "About Me" tab
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Other Threads in the Java Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC