There are entries in the database but whenever i enter any valid or invalid details in login form it always displays login failed. rs.next() is always returning false. Any solution for this problem ?
Code is as follows:-
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/logindata","root","");
#SuppressWarnings("deprecation")
String sql ="Select * from login Where UserName=' " + textField.getText()+ " 'and Password= ' " + passwordField.getText().toString()+"'";
PreparedStatement stmt =con.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();
String id=null;
String userId=null;
while(rs.next())
{
id=rs.getString("UserName");
userId=rs.getString("Password");
}
if(id!=null)
System.out.println("Login Success");
else
System.out.println("Login Failed");
con.close();
}
catch(Exception ex) {
System.out.println(ex);
}
Related
I work on an exame system with user login, admin login, etc.
When I check if the entered username (for example)
it doesn't return if it is already in the database
and creates it again!
try{
// Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
//imporrrrrrrrrrrrrrrrrrrrrrrtant
String selectquery = "select count(*)from uesrs where username='" + username + "'and password='" + password + "'";
Statement stat=con.createStatement();
System.out.println(selectquery);
ResultSet rs=stat.executeQuery(selectquery);
System.out.println(rs.next());
if(rs.next()==true){
infoMessage("Already registered ","Welcom");
}
else{
String insertQuery = "insert into uesrs values(null,'" + username_new_student.getText() + "','" + password_new_student.getText() + "','" + First_name_new_student.getText()+"')";
stat.executeUpdate(insertQuery);
infoMessage("info is inserted ","Alert!!!!!");
dispose();
user_login ul=new user_login();
ul.setLocationRelativeTo(null);
ul.setVisible(true);
}
}
catch (Exception ex) {
System.out.println(ex);
}
Once you call rs.next() inside System.out.println () it will move the pointer forward. Then when you call rs.next() inside if condition there will be no more results to show.
try{
// Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/big_project_3","root","");
//imporrrrrrrrrrrrrrrrrrrrrrrtant
String selectquery="select count(*)from uesrs where username='"+username+"'and password='"+password+"'";
Statement stat=con.createStatement();
System.out.println(selectquery);
ResultSet rs=stat.executeQuery(selectquery);
if(rs.next() ){
infoMessage("Already registered ","Welcom");
}
else{
String insertQuery="insert into uesrs values(null,'"+username_new_student.getText()+"','"+password_new_student.getText()+"','"+First_name_new_student.getText()+"')";
stat.executeUpdate(insertQuery);
infoMessage("info is inserted ","Alert!!!!!");
dispose();
user_login ul=new user_login();
ul.setLocationRelativeTo(null);
ul.setVisible(true);
}
}
catch (Exception ex) {
System.out.println(ex);
}
I have a issue with the delete button. When I enter nothing in the text field and press the delete button I'm not getting a popup menu as an exception.
private void billdeleteActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
int id=Integer.parseInt(billidtext.getText());
try (//step2 create the connection object
Connection con = DriverManager.getConnection("jdbc:oracle:thin:localhost:xe","hr","****")) {
Statement stmt=con.createStatement();
stmt = con.createStatement();
String sql = "DELETE FROM bill " +
"WHERE bid = ('"+id+"')";
int w=stmt.executeUpdate(sql);
if(w!=0)
JOptionPane.showMessageDialog(null,"Deleted Successfully!"); //this is displayed successfully
else
JOptionPane.showMessageDialog(null,"value does not exists!");// this is displayed successfully
supplieridtext.setText("");
//view trigger
String sql1="SELECT * FROM bill";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql1);
//STEP 5: Extract data from result set
billtable.setModel(DbUtils.resultSetToTableModel(rs));
rs.close();
//step5 close the connection object
}
}catch( ClassNotFoundException | SQLException e){
JOptionPane.showMessageDialog(null,"no value entered!");} //this line is not displayed when the text field is empty
}
if (!billidtext.getText().trim().isEmpty()) {
// Do query
}
As already stated, you'll need to trap the java.lang.NumberFormatException for int id=Integer.parseInt(billidtext.getText()); explicitly, as it's a "unchecked exception"
if (!billidtext.getText().trim().isEmpty()) {
try {
int id=Integer.parseInt(billidtext.getText();
// Do query
} catch (java.lang.NumberFormatException exp) {
JOptionPane.showMessageDialog(null,"Invalid value!");
}
} else {
JOptionPane.showMessageDialog(null,"no value entered!");
}
You should also be making use of PreparedStatements
Trying to use JDBC to handle some logic for validating if a user and password are in the DB and correct.
The method should return true if they are in the DB or false if not
I've tried changing the methods and it always either lets any user in, even if they dont exist, or no one in, even if they are in the DB.
Can someone explain how to fix this, funnily enough it was working the other day but I've changed something and unsure what...
JDBC code
public boolean checkUser(String username, String pass) {
boolean valid = false;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
String sql = "SELECT * FROM users WHERE (username = '" + username + "' AND password = '" + pass + "')";
System.out.println("lo " + sql);
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery(sql);
out.println(valid);
if(rs.next()) {
valid = true;
out.println(valid);
} else {
valid = false;
}
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}
I've included an image of the console output, the username test, with password tes is in the db.
Sorry it was another class which does the same thing I added the prepared too, it also always returns true or false regardless of if the condition is met.
public boolean checkUser(String username, String pass) {
boolean valid = true;
try {
//loading drivers for mysql
Class.forName("org.apache.derby.jdbc.ClientDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/workoutDB", "root", "root");
System.out.println("username = " + username);
System.out.println("pass = " + pass);
//String sql = "SELECT username FROM users WHERE (username = '" + username + "')";
//String sql2 = "SELECT password FROM users WHERE (password = '" + pass + "')";
//System.out.println(sql);
//System.out.println(sql2);
//Statement statement = con.createStatement();
//ResultSet rs = statement.executeQuery(sql);
//ResultSet rs2 = statement.executeQuery(sql2);
PreparedStatement ps = con.prepareStatement("select * from users where username=? and password=?");
ps.setString(1, username);
out.println("ps "+ps);
ps.setString(2, pass);
out.println("ps "+ps);
ResultSet rs = ps.executeQuery();
valid = !rs.next();
} catch (ClassNotFoundException | SQLException e) {
out.println(e);
}
out.println(valid);
return valid;
}
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/supermarket?username=root&password=");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM users WHERE username '" + username + "' AND password = PASSWORD( '" + password + "')");
rs.next();
if (rs.getRow() == 1) {
setVisible(false);
new Home().setVisible(true);
}
else {
jLabelAlarm.setText("Incorrect Username or Password!");
}
} catch (Exception e) {
}
I am new in java. This code belongs to login for connecting to MySQL server, but after running it not works properly.
("jdbc:mysql://localhost:3306/supermarket/root, "");
Just change the database connection code to this type.
I am trying to select data from a table using prepared statement. But it seems like I am getting syntax error which I cannot solve alone.
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/mydb";
String dbusername = "root";
String dbpassword = ""; // Change it to your Password
// Setup the connection with the DB
connection = DriverManager.getConnection(url, dbusername,
dbpassword);
String query = "SELECT * FROM admin WHERE username = ? AND password = ?";
try {
// connection.setAutoCommit(false);
selectUser = connection.prepareStatement(query);
selectUser.setString(1, username);
selectUser.setString(2, password);
// Execute preparedstatement
ResultSet rs = selectUser.executeQuery(query);
// Output user details and query
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: " + query);
boolean more = rs.next();
// if user does not exist set the validity variable to true
if (!more) {
System.out
.println("Sorry, you are not a registered user! Please sign up first!");
user.setValid(false);
}
// if user exists set the validity variable to true
else if (more) {
String name = rs.getString("name");
System.out.println("Welcome " + name);
user.setName(name);
user.setValid(true);
}
} catch (Exception e) {
System.out.println("Prepared Statement Error! " + e);
}
} catch (Exception e) {
System.out.println("Log in failed: An exception has occured! " + e);
} finally {
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
System.out.println("Connection closing exception occured! ");
}
connection = null;
}
return user;
}
I get following error.
Prepared Statement Error! com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '? AND password = ?' at line 1
But I don't see any error in that code line.
Change
ResultSet rs = selectUser.executeQuery(query);
to
ResultSet rs = selectUser.executeQuery();
when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);
what you want to do is use this method
ResultSet rs = selectUser.executeQuery();
You have already loaded your query inside the prepared statement here ,
selectUser = connection.prepareStatement(query);
so execute it by ,
ResultSet rs = selectUser.executeQuery();
Also read ,
How does PreparedStatement.executeQuery work?