-1

I have written a dbconnection.java class and it has a static block where i load the driver class

    static
{
    try
    {
        Class.forName(com.mysql.jdbc.Driver);
    }
    catch(ClassNotFoundException e)
    {
        e.printStackTrace();
    }
}

I know that this static block is written to register the driver. but even when i comment this static block and try to make a database connection it is getting connected.

So i wanted to know What Is The Importance or Significance of writing this static block.

kumuda
  • 499
  • 2
  • 8
  • 21
  • see http://stackoverflow.com/questions/19390942/jdbc-connection-alternative-to-class-forname-for-driver-loading – Leo Mar 19 '14 at 04:50
  • 1
    http://docs.oracle.com/javase/tutorial/jdbc/basics/connecting.html - note the part that explicitly explains this, and why it is no longer necessary in most cases. – Brian Roach Mar 19 '14 at 04:51

2 Answers2

1

(I'm answering this since we unfortunately do not have a RTFM close reason)

If you read the tutorial provided by oracle you'll find that this was once necessary but with many modern (JDBC 4.0) drivers, not so:

In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName. This methods required an object of type java.sql.Driver. Each JDBC driver contains one or more classes that implements the interface java.sql.Driver. The drivers for Java DB are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver, and the one for MySQL Connector/J is com.mysql.jdbc.Driver. See the documentation of your DBMS driver to obtain the name of the class that implements the interface java.sql.Driver.

Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)

(emphasis mine)

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
-2

Placing this code in static block is used to ensure that one process has the same driver. It's executed when the class is loaded (or initialized, to be precise, but you usually don't notice the difference). Details can be saw at this link

Community
  • 1
  • 1
TangQisen
  • 9
  • 1