通过搜索两列从数据库返回数据

时间:2017-03-28 15:20:34

标签: java sql database command line

当用户输入同时匹配cUsername和amp;时,我希望显示所有字段。 cPassword。在测试时,我的SQL语法出错(接近cPassword的地方)。有人可以提出这个问题吗?请注意我还没有通过SQL注入......

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;
}

1 个答案:

答案 0 :(得分:1)

除了你的错误之外,还有一些有问题的事情。该错误是由多个where子句引起的。通过更改:

来解决此问题

AND where cPassword likeAND cPassword like

我看到的另一件事是,应该与外卡一起使用,这样你可能想要改变:

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

为:

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

除非您正在寻找完全匹配,否则我会删除喜欢并使用“=”代替。