简体   繁体   中英

Null check in DB singleton

I have written one DB singleton class to provide single database connection and I am accepting the connection in another class what if it is null I have to null check condition please explain Tell me the best practice

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

another class

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

You can try

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM