返回语句中出现"error: cannot find symbol"错误

3

我想返回一个变量 String authServer,但是似乎做不到。

public static String getAuth () {
    Connection connection = null;
    try {
        connection = ConnectionConfig.getConnection();
        if (connection != null) {
            Statement query = connection.createStatement();
            ResultSet rs = query.executeQuery("SELECT auth FROM auth");
            while (rs.next()) {
                String authServer = rs.getString("auth");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return authServer;
    }
}

上面的代码出现了一个未知符号"authServer"的错误。
我做错了什么?

你已经在 while 循环的上下文中声明了 authServer,使其对方法的其余部分不可访问。 - MadProgrammer
好的,谢谢!我现在会尝试一下。 - David
3个回答

3
不要在while循环中声明authServer,它的作用域将在while循环结束后结束。你需要在while循环外声明。
public static String getAuth () {
    Connection connection = null;
    String authServer = "";
.....

然后从 while 循环中检索结果。


1
你正在while循环内声明authServer,导致在return语句处无法访问。 请在连接语句后面声明它,像这样:
Connection connection = null;
String authServer="";

然后在 while 循环中使用如下:
while (rs.next()) {
  authServer = rs.getString("auth");
}

1

由于authServer在上面的循环中声明,当您尝试在返回语句中使用它时,它不在范围内。

Java Made Easy有一个很好的Java变量作用域概述,可以帮助您更好地理解这个问题。

在您的特定情况下,请考虑以下修改以解决此问题:

public static String getAuth () {
    // Declare authServer with method scope, and initialize it.
    String authServer;
    Connection connection = null;
    try {
        connection = ConnectionConfig.getConnection();
        if (connection != null) {
            Statement query = connection.createStatement();
            ResultSet rs = query.executeQuery("SELECT auth FROM auth");
            while (rs.next()) {
                // Just assign to authServer here rather than declaring
                // and initializing it.
                authServer = rs.getString("auth");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return authServer;
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接