JDBC drivers automatically registered in modern Java
You said:
I was taught to use Class.forName
Your teacher is very much out-of-date.
In modern Java, you no longer need to call Class.forName. JDBC drivers are now automatically loaded via the Java Service Provider Interface (SPI). If curious about how this works, see this Question.
If your JDBC driver fails to be automatically registered, verify its inclusion within your project, or if in a Jakarta EE (Java EE) server, verify the proper location within that environment. You have not posted enough details about your development and deployment scenario for us to diagnose. And verify that you have the right version, which generally should support JDBC 4.x (4.3 is current).
If you continue to have trouble, write a throwaway console app that does nothing but connect to your database. Eliminate as much complexity and distraction as possible.
Regarding the code you show, I have no idea why you would want to be de-registering any drivers. Basically, all of the code you showed in your Question should be unnecessary.
DataSource
Furthermore, usually best to use a DataSource as the way to get connections to your database. A DataSource object holds the information required to connect: server address, port number, username, password, and various proprietary settings specific to your database server product.
I have written a few Answers on Stack Overflow with complete working examples for MySQL, Postgres, & H2. Like this one. I suggest you search for such example from me and the many other fine authors on Stack Overflow.
Here is one such example. The code shown here should be sufficient as the MySQL driver should be automatically loaded.
private DataSource configureDataSource ( )
{
System.out.println( "INFO - `configureDataSource` method. " + Instant.now() );
com.mysql.cj.jdbc.MysqlDataSource dataSource = Objects.requireNonNull( new com.mysql.cj.jdbc.MysqlDataSource() ); // Implementation of `DataSource`.
dataSource.setServerName( "db-mysql-lon2-722-do-user-89973-1.x.db.ondigitalocean.com" );
dataSource.setPortNumber( 24_090 );
dataSource.setDatabaseName( "defaultdb" );
dataSource.setUser( "scott" );
dataSource.setPassword( "tiger" );
return dataSource;
}
Usage:
Connection conn = myDataSource.getConnection() ;
Of course you should obtain a DataSource implementation that addresses your needs. For example, some provide fresh new connections while others provide connection pooling. Some are provided by the vendor of your database, and some are third-party.