2012-01-12 4 views
0

내가있어 클래스는 더 JDBC 작업 연결 개체를 반환합니다. 이 메서드의 결과가 "반환"인 경우 전역 연결 필드를 만들 가능성이 있습니까? 나는이 분야를 내가 필요한 곳에 사용하고 싶다.정적 전역 객체

public class Connection 
{ 
    public static Connection makeConnection() throws IOException, SQLException 
    { 
     try 
     { 
      Class.forName("org.postgresql.Driver"); 

      Properties props = new Properties(); 
      FileInputStream in = new FileInputStream("dataBase.properties"); 
      props.load(in); 
      in.close(); 

      String drivers = props.getProperty("jdbc.drivers"); 
      if(drivers != null) System.setProperty("jdbc.drivers", drivers); 
      String url = props.getProperty("jdbc.url"); 
      String username = props.getProperty("jdbc.username"); 
      String password = props.getProperty("jdbc.password"); 

      return DriverManager.getConnection(url, username,password); 
     } 
     catch (ClassNotFoundException e) 
     { 
     return null; 
    } 
     catch(IOException e) 
     { 
      return null; 
     } 
     catch(SQLException e) 
     { 
      return null; 
     }  
    } 
} 
+0

다음과 같은 의미가 있습니다. class Foo {static Connection conn = bar(); 정적 연결 표시 줄() {...}}'? –

+0

당신이 세계에 의해 당신의 클래스에 정적 인 것을 의미한다면 그렇습니다. JDBC 커넥션 객체는 이런 식으로 사용하도록 만들어지지 않았다. – Perception

답변

0

당신이 할 수 있습니다 :

class Foo { 

    public static Connection conn = bar(); 

    private static Connection bar() { 
     ... 
    } 
} 

당신이 원하는 무엇인가요?

+0

그건 괜찮 겠지 만, 컴파일러는 conn 선언에 맞지 않는 예외 때문에 예외를 반환합니다. 나는 뭔가를 놓치고 있는가, 아니면 이것이 죽은 원의 왕인가? –

+0

'bar()'가 예외를 잡아서'null '을 반환하거나 런타임 예외를 던져 프로그램을 중단시키는 경우에 작동합니다. –

1

가능하지만 연결 팩토리가 연결보다 좋습니다. 그러나 정적 변수는 연결의 수명주기 제어에 적합하지 않습니다.

동시 연결, 시간 초과 감지, 재활용 연결 재사용, 연결 해제 된 연결 자동 제거와 같은 많은 문제가 연결 풀에서 처리됩니다.

0

이 연결을 처리하는 방법 하지입니다 ...하지만 어떻게 문제의 유사한 종류를 해결하는 당신에게 아이디어를 줄 수 있습니다

public class Wombat 
{ 
    public static Wombat getWombat() 
    { 
     if (theWombat == null) 
     theWombat = new Wombat(); 
     return theWombat; 
    } 

    private static Wombat theWombat= null; 
} 
0

당신은 정적 초기화 블록에서 정적 변수를 초기화 할 수 있습니다 :

class Foo { 
    public static Connection conn; 

    static { 
     try { 
     conn = makeConnection(); 
     } catch(...) { 
     ... 
     } 
    } 
}