2017-12-15 2 views
0

데이터베이스에 연결 한 다음 쿼리를 보내고 대답을 얻는 프로그램이 있습니다. 메인 클래스에서 연결하고 쿼리 할 때 모든 것이 정상 이었지만 3 개의 다른 클래스를 만들려고 할 때 프로그램이 작동하지 않습니다. 쿼리에서 connect 함수를 호출 한 다음 main에서 쿼리 함수를 호출하려면 어떻게해야합니까?다른 하나의 메서드 호출

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 
} 

답변

0

그래서 당신의 함수는 연결을 반환해야

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(); 
+0

이 효과가 있다면 의견을 보내주세요 ... 아직 문제가 있다면 도움을 드릴 수 있습니다. – vofili

관련 문제