Check username and password with MySQL - java

I am trying to verify username and password with MySQL. But it's not working. I can't find the problem. Can anybody help me fix it?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String user = jTextField1.getText();
char[] pass = jPasswordField1.getPassword();
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
while (rs.next())
{
if (user.equals(rs.getString("username")))
{
if (pass.equals(rs.getString("password")))
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}
Actually I think it is not checking the enteries with username and password in database. am I right?

Firstly, select by username, then hash the user entered password en check if it matches the hashed password in the database. I suggest something like SHA-2
I also suggest you write classes to handle your code, i.e a User class..
You also forgot to close your ResultSet
One more thing, use PreparedStatement

You are checking for password and username match 2 times.
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
There you already check the password and user, First you shuld check if the password its not stored as MD5 or any other hash type
After that sql you only need to check if its returns any row like #Prabhakaran says

Check code which is written is connecting to database, password is not there in the below code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Second is check the user and pass variable is getting the value from the action event.

Do like this
Statement stat = con.createStatement();
user = user.toLowerCase();
pass = pass.toLowerCase();
String sql = "Select * from tbl_User Where LOWER(username)='" + user + "' and LOWER(password)='"+pass+"'";
rs = stat.executeQuery(sql);
if(rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}

First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will try to help you out.
1- It seems your connection variable missing the "Connection" try this :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"DATABASENAME"?useTimezone=true&serverTimezone=UTC","USERNAME","PASSWORD");
2 - You already made the if statement to the query in the beginning, so you don't have to start all over again with You can simply type :
if (rs.next()) {
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
} then carry on with the exception part
this is the code :
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
if (rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}`

Related

Sign-In as different users types

I'm very new to JAVA so this is probably an easy solution.
I'm looking to design a login system using differnt users from a database.
They are seperated by a "Yes" column in the database.
It currently signs in the manager using the IF statement but stops there and won't sign in when using credetials of a staff member.
signIn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try{
Class.forName(DRIVER);
// Connection to the Database
con = DriverManager.getConnection(DATABASE_URL,"root","");
// Gets text from textfields and assigns them to variables
s1 = tfUsername.getText();
s2 = tfPassword.getText();
Statement st = con.createStatement();
// SQL Statements
st.executeQuery("SELECT * FROM login WHERE UName= '"+s1+"' and PWord = '"+s2+"'");
// Extracts data from statement to a result set
ResultSet rs = st.getResultSet();
if (rs.next())
{
String Username = rs.getString("UName");
String Password = rs.getString("PWord");
String staff = rs.getString("Staff");
String management = rs.getString("Management");
if(Username.equals(s1) & Password.equals(s2) & management.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1 );
ManagerDashboard.main(args);
signInFrame.setVisible(false);
}
if(Username.equals(s1) & Password.equals (s2) & staff.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1);
StaffDashboard.main(args);
signInFrame.setVisible(false);
}
}
else
{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
// SQL Catch block to catch errors
catch(SQLException s){
}
// Catch block to catch ActionListener errors
catch (Exception e1){
}
};
});

how to create login page & new login acount creating?

try {
Connection c = DB.getCon();
Statement s = c.createStatement();
s.executeUpdate("INSERT INTO login(LogID, UserName, Password) VALUES('"+jTextField1.getText()+"', '"+jTextField2.getText()+"', '"+jPasswordField1.getPassword()+"')");
} catch (Exception e) {
e.printStackTrace();
}
autoGen();
clear();
I code this to my new login account creating form but the password is save like encrypted then i code login page like this it want do anything and there is no errors
String user = jTextField1.getText();
String pass = new String(jPasswordField1.getPassword());
try {
ResultSet rs = DB.getCon().createStatement().executeQuery("select * from login where UserName='" + user + "' and Password = '" + pass + "'");
if (rs.first()) {
if (rs.first()) {
Main_Page pat1 = new Main_Page();
pat1.setVisible(true);
Login_Page.this.setVisible(false);
} else {
jLabel6.setText("Login faild");
}
}`enter code here`
} catch (Exception e) {
e.printStackTrace();
}
please anyone help me
Examining the code you provided, one problem appears to be that you have redundant/nested if statements with no else clause on the outer if statement. This would cause the behavior you described if the account was not found in the query. Try removing the outer if statement.

login unsuccessfull on clicking button?

I have a table:
create table User1(Username varchar2(20) ,
First_Name varchar2(20) ,
Last_Name varchar2(20) ,
Password varchar2(20) ,
Date_Of_Birth Date )
following jdbc code::
if(e.getSource()==submit)
{
Connection con=null;
ResultSet rs=null;
PreparedStatement st=null;
try
{
Class.forName("oracle.jdbc.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1522:xe", "hr", "hr");
st=con.prepareStatement("select count(1) from User1 where Username = ? and Password = ? ");
//st.setParameter(1, text1.getText());
//st.setParameter(2, p1.getText());
st.setString(1,text1.getText());
st.setString(2,text1.getText());
rs= st.executeQuery();
//String t1=text1.getText();
//String t2= p1.getText();
while(rs.next())
{
if (rs.getInt(1) == 1)
{
new Rec_options();
}
}
}
catch(SQLException ee)
{
System.out.println(ee);
}
catch(Exception e1)
{
System.out.println(e1);
}
finally
{
try
{
rs.close();
con.close();
st.close();
}
catch(SQLException eee)
{
System.out.println(eee);
}
}
}
Is there a problem in while loop ? cause after entering username and password when i click on submit button ,another page "Rec_options" should get opened,but here nothing's happening nor am i getting any error or something in cmd.I'm entering the correct username and password.
Please help!!
Thanks..
You've used "st.setString(1,text1.getText());" twice. I think you should change second one to password string.
You seem to have a typo in your construction of the prepared statement:
st.setString(1,text1.getText());
st.setString(2,text1.getText()); // <---- You are passing your username twice.
Try to use variable name that indicate its type and purpose
txtuser
txtpassword

Exhausted Result Set

I am developing a project for Online Banking System. I want to retrieve a data from database using JDBC. However, it is showing Exhausted result exception though the query is returning a row in SQLPlus. Please Help. Here's the Code:
try
{
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "hr", "XXXXXX");
String pass = 'sid';
String user = 'sid';
String accountnumber = '2345';
String sql = "select * from user_info where account_number=?";
s1 = con.prepareStatement(sql);
s1.setString(1,accountnumber);
rs1 = s1.executeQuery(sql);
rs1.next();
if(user.equals(rs1.getString("user_name")))
{
if(pass.equals(rs1.getString("password")))
{
if(accountnumber.equals(rs1.getString("account_number")))
{
new AccountInformation(accountnumber).setVisible(true);
}
else
{
JOptionPane.showMessageDialog(this, "Account Number is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "Password is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "User Name is Incorrect");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
You threw away your bind parameter when you passed the SQL to Statement#executeQuery - use this one from PreparedStatement...
rs1=s1.executeQuery();
// rs1=s1.executeQuery(sql);
// check if you got a row
if (rs1.next()) {
// as before....
}

com.microsoft.sqlserver.jdbc.SQLServerexception:incorrect syntax near'='

I'm getting the error in the first line i guess! Please help me out in dealing with it. I'm basically trying to execute a query through my front end
try {
ResultSet rs=st.executeQuery("select *from Login Username ='"+username+"' and Password '"+password+"'");
rs.last();
int counter = rs.getRow();
if (counter==1){
JOptionPane.showMessageDialog(null,"Username and Password Correct","Username and Password Correct",JOptionPane.INFORMATION_MESSAGE);
this.setVisible(false);
new Menu().setVisible(true);
hide();
}else{
jt_username.setText("");
jp_password.setText("");
JOptionPane.showMessageDialog(null,"Error","Username and Password Incorrect",JOptionPane.INFORMATION_MESSAGE);
}
}
catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
}
Your SQL is missing the WHERE keyword. Try this on for size:
ResultSet rs=st.executeQuery("select * from Login WHERE Username ='"+username+"' and Password= '"+password+"'");

Categories