从内部返回逻辑/捕获块

发布于 2025-02-04 14:24:17 字数 1056 浏览 5 评论 0 原文

public String returnFirstName() throws SQLException {
    String Username = username.getText();
    String Password = String.valueOf(password.getPassword());
    connection = DriverManager.getConnection(jdbcURL, user, SQLPassword);
    statement = connection.createStatement();
    try {
        resultSet = statement.executeQuery("SELECT * FROM users WHERE username="
                + "'" + Username + "'" + " AND password=" +
                "'" + Password + "'" + ";");
        FirstName = resultSet.getString("first_name");
    } catch (Exception exception) {
        error = true;
        exception.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        if (error) System.out.println("Error");
    }
    return FirstName;
}

您好,所以我遇到了一个问题,我试图返回该值,从数据库中获取,但是FirstName的值是NULL,而Try Block中的语句没有效果。有什么方法可以将值返回,并在try块中逻辑。 (已经声明了一个名称变量) 谁能帮我吗?提前致谢!

public String returnFirstName() throws SQLException {
    String Username = username.getText();
    String Password = String.valueOf(password.getPassword());
    connection = DriverManager.getConnection(jdbcURL, user, SQLPassword);
    statement = connection.createStatement();
    try {
        resultSet = statement.executeQuery("SELECT * FROM users WHERE username="
                + "'" + Username + "'" + " AND password=" +
                "'" + Password + "'" + ";");
        FirstName = resultSet.getString("first_name");
    } catch (Exception exception) {
        error = true;
        exception.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
        }
        if (error) System.out.println("Error");
    }
    return FirstName;
}

Hello, So I have the problem where I am trying to return the value, fetched from the database but the value of firstname is null, and the statements in the try block have no effect. Is there any way to return the value, with the logic in the try block. (The firstname variable is already declared)
Can anyone help me on this? Thanks in advance!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

画中仙 2025-02-11 14:24:17

resultset.getString()如果存在 first_name 列存在,则不会抛出NullPoInterException。

一种可能的解决方案是:

FirstName = resultSet.getString("first_name");
if (FirstName == null) {
        throw new NullPointerException();
}

我还会强烈建议更改您编写查询的方式。 使用准备的语句作为当前方法使您的数据库容易受到注射攻击。

准备好的语句是通过绑定变量为用户输入提供占位符的SQL语句。执行语句后,将单独提供用户输入,以确保将数据库从未被欺骗到执行用户输入为代码中。

这是您查询的部分实现,我将其余的供您弄清楚:

PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT * FROM users WHERE username=?");
prep.setString(1, Username);
return preparedStatement.executeQuery();

resultSet.getString() will not throw a NullPointerException if the first_name column exists.

One possible solution to this would be:

FirstName = resultSet.getString("first_name");
if (FirstName == null) {
        throw new NullPointerException();
}

I would also highly recommend changing the way the way you have written your query. Use Prepared statements as the current approach makes your database susceptible to injection attacks.

Prepared statements are SQL statements that provide placeholders for user input through bind variables. When the statement is executed, the user input is supplied separately to ensure the database is never tricked into executing user input as code.

Here is a partial implementation of your query, I will leave the rest for you to figure out:

PreparedStatement preparedStatement = connection.prepareStatement(
"SELECT * FROM users WHERE username=?");
prep.setString(1, Username);
return preparedStatement.executeQuery();
心欲静而疯不止 2025-02-11 14:24:17

处理数据库错误的正确方法是……根本不捕获它。

请注意此行中的最后两个关键字:

public String returnFirstName() throws SQLException {

抛出SQLEXCEPTION 部分表示您不必在代码中捕获任何例外投掷条款告诉任何需要决定如果数据库检索出于任何原因失败的呼叫代码。那是一件好事。这就是应该写出应用程序的方式。

这也意味着您不需要 catch 块。实际上,如果将连接和语句放在 try-with-with-resources语句

public String returnFirstName() throws SQLException {
    String Username = username.getText();
    String Password = String.valueOf(password.getPassword());

    try (Connection connection = DriverManager.getConnection(jdbcURL, user, SQLPassword);
         Statement statement = connection.createStatement()) {


        ResultSet resultSet = statement.executeQuery("SELECT * FROM users WHERE username="
                + "'" + Username + "'" + " AND password=" +
                "'" + Password + "'" + ";");
        return resultSet.getString("first_name");
    }
}

通过声明之后的括号内的连接和语句对象, try ,我们告诉java时,当Java在尝试块结束。如果代码成功完成,并且发生异常,则会发生这种情况。 (resultset 当关闭其相应的语句时。)

而不是试图忽略异常并为firstName选择一些“特殊”值,而是让呼叫代码决定如果无法检索该值,该怎么办。这允许您的方法每次可靠地返回有效的值。如果发生错误,该方法根本不会返回。取而代之的是,它将传播基本的sqlexception。调用您方法的代码可以确定,如果完全返回值,则是一个有效的值。

(我故意在这里没有解决安全含义,例如SQL注入和未解决的密码,因为这似乎是一项任务或练习练习,并且安全问题将超出范围。)

The proper way to handle a database error is… not to catch it at all.

Notice the last two keywords in this line:

public String returnFirstName() throws SQLException {

The throws SQLException part means you don’t have to catch any exceptions in your code. The throws clause tells any calling code that it must decide what to do if the database retrieval fails for any reason. That is a good thing. That is how applications should be written.

It also means you don’t need a catch block. In fact, you can also remove the finally block, if you place your Connection and Statement in a try-with-resources statement:

public String returnFirstName() throws SQLException {
    String Username = username.getText();
    String Password = String.valueOf(password.getPassword());

    try (Connection connection = DriverManager.getConnection(jdbcURL, user, SQLPassword);
         Statement statement = connection.createStatement()) {


        ResultSet resultSet = statement.executeQuery("SELECT * FROM users WHERE username="
                + "'" + Username + "'" + " AND password=" +
                "'" + Password + "'" + ";");
        return resultSet.getString("first_name");
    }
}

By declaring the Connection and Statement objects inside parentheses after try, we are telling Java to automatically close them when the try block ends. This will happen both if the code completes successfully, and if an exception occurs. (The ResultSet is automatically closed when its corresponding Statement is closed.)

Instead of trying to ignore an exception and pick some “special” value for firstName, let the calling code decide what to do if the value cannot be retrieved. This allows your method to reliably return a valid value every time. If an error occurs, the method simply never returns at all; instead, it will propagate the underlying SQLException. The code which calls your method can be certain that if a value was returned at all, it is a valid value.

(I am deliberately not addressing the security implications here, such as SQL injection and unhashed passwords, since this appears to be an assignment or practice exercise, and security concerns would be out of scope.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文