从一个方法调用另一个方法

Call one method from another one

我有这样一个程序,它连接到数据库,然后发送查询并得到答案。当我在主 class 中进行连接和查询时一切正常,但是当我尝试创建 3 个不同的 class 时我的程序不起作用。如何从查询中调用连接函数,然后从主函数中调用查询函数?

public class App {

public static void connect() throws IOException {

    Connection c = null;
    try {
        Class.forName("org.postgresql.Driver");
        c = DriverManager.getConnection(dbName, userName, password);
    } catch (Exception e) {
        e.printStackTrace();
        System.err.println(e.getClass().getName() + ": " + e.getMessage());
        System.exit(0);
    }
    System.out.println("Opened database successfully");
}

public static void query() {

    Connection c = connect();   // call function - error
    Statement stmt = c.createStatement();
    stmt = c.createStatement();
    String query = "Select count(distinct country) sum from customers";
    ResultSet rs = stmt.executeQuery(query);
    query = "SELECT * from country";
    rs = stmt.executeQuery(query);
    while (rs.next()) {
        String country = rs.getString("country");
        String netamount = rs.getString("netamount");
        System.out.println(country + " " + netamount);
        System.out.println();
    }
    rs.close();
    stmt.close();
    c.close();
}

public static void main(String[] args) {

    query();  // call function
}

所以你的函数需要return一个连接

试试这样重写

public static Connection connect() throws IOException {
BufferedReader br = new BufferedReader(new FileReader("login.txt"));

dbName = br.readLine();
userName = br.readLine();
password = br.readLine();

Connection c = null;
try {
    Class.forName("org.postgresql.Driver");
    c = DriverManager.getConnection(dbName, userName, password);
} catch (Exception e) {
    e.printStackTrace();
    System.err.println(e.getClass().getName() + ": " + e.getMessage());
    System.exit(0);
}
System.out.println("Opened database successfully");
return c;

}

然后您的查询函数将按预期工作,尤其是行

Connection c = connect();