繁体   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