简体   繁体   中英

JDBC/Connectorj: When to load drivers?

I was wondering what is the 'correct' way to load drivers for my Java servlet.

Currently, I have a InitializeDrivers() function that I call at the beginning of my application.

public static boolean InitializeDrivers()
{
    try {
        Class.forName("com.mysql.jdbc.Driver");
        return true;
    } catch (ClassNotFoundException ex) {
        // log error
        return false;
    }
}

After that is done, I go on performing my various requests/inserts to the database depending on the HTTP request that was received. However, since my servlet can receive hundreds of requests per seconds, InitializeDrivers() will be called one time for each request.

Is it the correct way to do this, or is there a way to load the drivers only once?

When you're using a database in a servlet, then it is better to let the servlet container manage database connections through a connection pool instead of directly getting a database connection yourself in the servlet.

Opening a connection to a database server is a relatively slow operation. Also, the number of connections that a database can handle at the same time is limited. Your application will be slow and not very scalable when you open a database connection each time you need to access the database. Also, database connections are not thread-safe, so you cannot store a database connection in a static member variable of the servlet and use that every time.

A connection pool manages a number of open connections for you (so that you don't have to open the connection each time you need to access the database), and manages the number of connections that are open at the same time. In for example Apache Tomcat, you can configure this so that you lookup a javax.sql.DataSource object via JNDI, which you then use to get a Connection object from.

This page explains how to configure Tomcat and use a DataSource in your servlet:

JNDI Datasource HOW-TO

If you do not want to do this and you want to continue using database connections from your servlet (which I do not recommend), then you could load the driver in a static initializer block in your servlet:

public class MyServlet extends HttpServlet {
    static {
        Class.forName("com.mysql.jdbc.Driver");
    }

    // ...
}

Note that in JDBC 4.0, loading the driver explicitly is not necessary anymore; JDBC will automatically find drivers as long as they in the classpath.

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