java - sqlite 查询的结果集没有 rs.next()
问题描述
在我的代码中,我试图获取一个用户名为“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));
}
}
解决方案
首先,您应该使用PreparedStatement
而不是Statement
参数化查询。这样做的两个重要优点是:
您的应用程序不会受到 SQL 注入的影响。
您不需要
'
明确地放置文本值。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
.
推荐阅读
- javascript - 基于数组对象键值需要setState
- python - 绘制 yticks 以获取来自两列而不是仅一列的数据
- python - 在 Python 中绘制具有 2D 向量条目的函数
- javascript - 如何重新启动倒数计时器以及为什么它会跳过几秒钟
- powerbi - 使用多个标准选择计数
- javascript - 无法对未安装的组件 REACT-NATIVE 执行 React 状态更新
- python - PyCharm。意外的参数 可能的被调用者
- php - PHP 查询显示空白页
- cluster-analysis - 整群抽样中的问题:“与负下标混合”
- html - 如何将文本居中放置在图像上方