user8275100
user8275100

Reputation:

sql query returning no results (when it should) with no errors

I am trying to query the database to select users that exist in the database (log in).

Config.java class
public class config {
protected static String dbhost = "localhost";
protected static String dbport = "1433";
protected static String dbuser = "root";
protected static String dbpass = "";
protected static String dbname = "BenxHR";
}

my database handler classs:
public class DbHandlers extends config{

protected Connection dbconnection;

public Connection getConnection(){
 final String ConnectionString = "jdbc:sqlserver://" + config.dbhost + ":" + 

config.dbport + ";databaseName=" + config.dbname;
     try{
         Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

     } catch (ClassNotFoundException e) {
         System.err.println(e.getMessage());
     }

     try {
         dbconnection = DriverManager.getConnection(ConnectionString, config.dbuser, config.dbpass);
     } catch (SQLException e){
         System.err.println(e.getMessage());
     }
     return dbconnection;
    }
}

The query:
private void clickLogin(MouseEvent event) throws SQLException {     
    String query1 = "SELECT * FROM users WHERE username  = ? OR email = ? 
AND password = ?";
    con = handler.getConnection();
    pst = con.prepareStatement(query1);
    pst.setString(1, usernameField.getText());
    pst.setString(2, usernameField.getText());
    pst.setString(3, passwordField.getText());

    ResultSet rs = pst.executeQuery();

    if(!rs.isBeforeFirst()){
        System.out.println("Failed.");
    } else {
        System.out.println("Success");
    }
}

So I have one class which contains the database information such as ip, port, user and password. I also have a SELECT statement which selects database items and returns a row value depending on whether it comes back successful or not.

Everything seems to be working and no exceptions are thrown, but no matter which username and password I use, it prints the line 'success'.

Does anyone have any reasons why this might be happening?

Upvotes: 0

Views: 2244

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269773

Good for using parameters. Bad for passing passwords around. You should be encrypting them and only passing them in an encrypted state.

This will not fix your problem, but your query is not doing what you intend. It is doing:

WHERE username  = ? OR (email = ? AND password = ?)

Presumably, you are new to SQL. I recommend that you use parentheses whenever you are mixing ORs and ANDs in a condition. Presumably you intend:

WHERE (username  = ? OR email = ?) AND password = ?)

As I say, though, that will not return rows if your version did not return rows.

Upvotes: 1

Related Questions