mardi 16 novembre 2021

Unable to use JDBC without using deprecated Class.forName method

I'm new to dynamic web development and having some problems trying to get JDBC to work on one of my Tomcat servlets. I have the mysql-connector-java-8.0.27.jar in my src/main/webapp/WEB-INF/lib folder and am just simply connecting to the database using the following code:

private Connection database;

public void init() throws ServletException {
    try {
        //Connect to database
        database = DriverManager.getConnection("jdbc:mysql://localhost:3306/auth", "root", "password");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

When I run my Dynamic Web Project and click a button that executes this servlet, I get the following error:

SQLException: No suitable driver found for jdbc:mysql://localhost:3306/auth. The error points to my DriverManager.getConnection() line in my servlet.

This was really confusing me since I am able to run the same code just fine in a normal Java Project in eclipse. I new it had to be the fact that I am using a Dynamic Web Project. The jar file is most definitely added as an external archive.

I was able to get my code to finally work by adding this line:

Class.forName("com.mysql.cj.jdbc.Driver").newInstance(); //ADD THIS LINE!
database = DriverManager.getConnection("jdbc:mysql://localhost:3306/auth", "root", "password");

I looked it up and using this method has been deprecated for a long time and hasn't been necessary since Java 6 and JDBC v4. I am most definitely running Java 16 and JDBC v8, so I have no idea why this line is necessary for me. Is it the fact that my jar file is under "Web App Libraries"? I'm just not sure, but I feel uncomfortable not knowing why I have to use a method that has been deprecated for years. Any help would be appreciated.




Aucun commentaire:

Enregistrer un commentaire