Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Without using Class.forName...

 
Jyothi Lature
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is there a way to connect to the database without using Class.forName (" ") in java?
 
vinod sharma
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());
 
Julian Kennedy
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Drivers can also be registered by including the class names in the jdbc.drivers system property. However, the current preferred method of connection to a JDBC database is using a DataSource object. Here is an example:

Is there a particular reason for your question?

Hope you find this useful.

Jules
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by vinod sharma:
DriverManager.registerDriver( new oracle.jdbc.driver.OracleDriver());


This is not recommended, it can result in the Driver being registered twice. Once by the Driver class when the class loads in the ClassLoader, and the second time since you register it explicitly. 99.9% of the time it wont be an issue, but it means DriverManager.deregisterDriver(Driver driver) won't work, it will only remove one instance.

If you are prepared to hard-code the driver class, using Class c = oracle.jdbc.driver.OracleDriver.class will work the same as Class.forName(...), but is a pointless substitution, you might as well use Class.forName(...).

In the API docs for the DriverManager class, it shows the other preferred way, which is to include the Driver class on the command line with the -Djdbc.drivers=(colon separated fully qualified class list). This will automatically load the listed Drivers for you, without needing Class.forName(...) or any equivalent. The -D option could also be added to the Java system properties file, but this probably isn't a good idea. You may need to change a Driver and forget to update the file, and it would be nearly impossible to debug.

Julian is correct in saying the using a DataSource is the real preferred way, and I've heard mention that the DriverManager mechanism may be removed or deprecated in future in preference to using DataSources.
 
Jyothi Lature
Ranch Hand
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you all...!

It was asked in one of the interviews....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic