user3079838
user3079838

Reputation: 83

Returning Data from database by searching through two columns

I am looking to display all fields when a user input matches both cUsername & cPassword. When testing this, I get an error in my SQL Syntax (near where cPassword like). Can anybody suggest the issue? Please be aware I have not gone through SQL Injection yet...

public Car getLogin(String searchUser, String searchPass) {
    Car foundCar1 = new Car();
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection conn = DriverManager.getConnection(url + dbName, userName, password);
        statement = conn.createStatement();
        resultSet = statement.executeQuery("select * from eflow.registration where cUsername like '" + searchUser
                + "' AND where cPassword like '" + searchPass + "'");

        while (resultSet.next()) {
            foundCar1 = new Car(resultSet.getInt("cID"), resultSet.getString("cLicense"),
                    resultSet.getInt("cJourneys"), resultSet.getString("cUsername"),
                    resultSet.getString("cPassword").toString());
        }
        conn.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return foundCar1;
}

Upvotes: 0

Views: 23

Answers (1)

Anand
Anand

Reputation: 1123

There are a couple of problematic things here apart from your error. The error is caused by multiple where clauses. Fix this by changing:

AND where cPassword like to AND cPassword like

The other thing I see is that like should be used in conjunction with wild cards so you may want to change:

resultSet = statement.executeQuery("select * from eflow.registration where cUsername like '" + searchUser
            + "' AND where cPassword like '" + searchPass + "'");

to:

resultSet = statement.executeQuery("select * from eflow.registration where cUsername like '%" + searchUser
            + "%' AND cPassword like '%" + searchPass + "%'");

Unless if you are looking for exact match, in which case I would remove like and use "=" instead.

Upvotes: 1

Related Questions