2017-10-05 46 views
0

我寫了一個DB單類,以提供單一的數據庫連接,我接受在另一大類連接,如果它是空我得空檢查條件請解釋 告訴我最好的做法空檢查

public class DBSingleton { 
    private static final DBSingleton ONLY_ONE = new DBSingleton(); 
    private Connection connection = null; 
    private DBSingleton() { 
     try { 
      Class.forName("com.mysql.jdbc.Driver"); 
      connection = DriverManager.getConnection("url", "username","pwd");// SQLException 
     } catch (ClassNotFoundException | SQLException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static DBSingleton getInstance() { 
     return ONLY_ONE; 
    } 

    public Connection getcon() { 
     return connection; 
    } 
} 

另一個類

private Connection con = DBSingleton.getInstance().getcon(); 
+1

不確定你在問什麼 - 如何編寫單例? –

+0

我已經寫了DB Singleton類來提供單個數據庫連接如果它是null –

+0

爲什麼你不拋出異常? –

回答

0

您可以嘗試

public class BDConnection { 
private static final Logger LOGGER = LoggerFactory.getLogger(BDConnection.class); 
private static Connection connection = null; 

public static Connection getConnection() { 
    if(connection == null){ 
     createConnection(); 
    } 
    return connection; 
} 

private static void createConnection() { 
    try { 
     Class.forName(ImportExportFilesUtils.getResourceMessage("driver.name")).newInstance(); 
     connection = DriverManager.getConnection(ImportExportFilesUtils.getResourceMessage("database.test.url"), ImportExportFilesUtils.getResourceMessage("database.test.username"), 
       ImportExportFilesUtils.getResourceMessage("database.test.password")); 
    } catch (Exception ex) { 
     LOGGER.error("Cannot load the driver for ojdbc", ex); 
    } 
} 

public static void closeConnection() { 
    if (connection != null) { 
     try { 
      connection.close(); 
     } catch (SQLException e) { 
      LOGGER.error("Cannot close the connection with the database", e); 
     } 
    } 
} 

}

+0

好編輯@ N00b Pr0grammer。我希望這會有所幫助:) thx –

+0

我不應該關閉 –

+0

請解釋爲什麼你的代碼是答案 –