•
•
•
•
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
![]() |
| |
•
•
Join Date: Aug 2007
Posts: 167
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: 167
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
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 = ?"
);
I AM the 12th CYLON
![]() |
•
•
•
•
•
•
•
•
DaniWeb Java Marketplace
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
- Previous Thread: Having problems rotating Shapes in JPanel
- Next Thread: Variation of the Monte Carlo form of finding Pi... I'm having a bit of trouble



Hybrid Mode