Win a copy of Kubernetes in Action this week in the Cloud/Virtualization forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

What is the difference between Class.forName() and DriverManager.registerDriver() ?  RSS feed

 
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a difference in the following two ways of loading a JDBC driver?
1. Class.forName("aJDBCDriver");
2. DriverManager.registerDriver(new aJDBCDriver());
Thanks.
Bruce
 
Ranch Hand
Posts: 1512
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Class.forName() explicitly loads the driver class.
DriverManager.registerDriver() should be called automatically by the driver when it's loaded. It registers the driver with the DriverManager.
The recommended way is the first one.

Bosun
 
Bruce Jin
Ranch Hand
Posts: 672
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Bosun.
Bruce
 
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Bosun,
can you explain that some what deeply?
does drivermanager internally uses class.forname to load the driver?
 
Ranch Hand
Posts: 333
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Originally posted by daya mukiri:
Hi Bosun,
can you explain that some what deeply?
does drivermanager internally uses class.forname to load the driver?



No. In Java, classes are almost always loaded implicitly, when they're referenced, and not before. When DriverManager.registerDriver(new aJDBCDriver()); is called, "new aJDBCDriver()" loads the driver (and if the driver conforms to the JDBC specification, loading the driver causes it to call DriverManager.registerDriver() upon itself!! ).

Explicitly loading a class with class.forname is a very rare thing, used to select a class at run time, instead of at compile time. It is used in JDBC so that people can write code that will work with any database driver.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!