簡體   English   中英

DB單例中的Null檢查

[英]Null check in DB singleton

我已經編寫了一個數據庫單例類來提供單個數據庫連接,並且我在另一個類中接受該連接,如果它為null,則必須具有null檢查條件,請解釋一下告訴我最佳實踐

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

你可以試試

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);
        }
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM