sqlite查询的结果集没有rs.next()

时间:2020-07-25 15:53:50

标签: java sqlite

在我的代码中,我试图获取一个用户名=“ Jason”且密码为“ 1234”的用户。但是,我正在使用的查询未在Java中返回任何值。另一方面,当我在SQL工作台上编写相同的查询时,它将返回一行。

    @FXML
    private TextField tf_username;

    @FXML
    private TextField pf_password;

    @FXML
    void logIn(MouseEvent event) throws SQLException, IOException {
       String username = tf_username.getText();
       String password = pf_password.getText();
       String checkPassSql = "select * from users where username" + " = '"+username+"'and password = '"+password+"' ";
       
       Connection connection = DbConnect.getInstance().getConnection();
       
       Statement statement = connection.createStatement();
       
       ResultSet rs = statement.executeQuery(checkPassSql);
              
       
       if(rs.next()){
        //change the next line from signUp scene to home scene  
        Parent root = FXMLLoader.load(getClass().getResource("home.fxml"));
        Node node = (Node) event.getSource();
        Stage stage = (Stage) node.getScene().getWindow();
        stage.setScene(new Scene(root)); 
       }
       
       
       
    }

This is the expected result set from the SQL workbench

1 个答案:

答案 0 :(得分:0)

首先,对于参数化查询,应使用PreparedStatement而不是Statement。这样做的两个重要优点是:

  1. 您的应用程序将不受SQL注入的攻击。<​​/ p>

  2. 您无需在文本值周围明确放置'

    String sql = "SELECT * FROM users WHERE username=? AND password=?";
    
    PreparedStatement preparedStatement = connection.prepareStatement(sql);
    
    preparedStatement.setString(1, username);
    preparedStatement.setString(2, password);
    
    ResultSet rs = preparedStatement.executeQuery();
    

您的代码似乎在哪里失败?

如果执行以下代码,

public class Main {
    public static void main(String[] args) {
        String username = "Jason";
        String password = "1234";
        String sql = "select * from users where username" + " = '" + username + "'and password = '" + password + "' ";
        System.out.println(sql);
    }
}

您将获得以下输出:

select * from users where username = 'Jason'and password = '1234' 

与您在SQL工作台上执行的操作不同。为了匹配它,您的代码应如下所示:

String sql = "select * from users where username" + " = \"" + username + "\" and password = \"" + password
                + "\"";

那将被转换为以下内容:

select * from users where username = "Jason" and password = "1234"

与您在SQL工作台上测试的内容相同。

但是,正如我前面已经提到的,使用PreparedStatement代替Statement

相关问题