我寫了一個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();
不確定你在問什麼 - 如何編寫單例? –
我已經寫了DB Singleton類來提供單個數據庫連接如果它是null –
爲什麼你不拋出異常? –