Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes JDBC and Relational Databases and the fly likes JDBC Connection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "JDBC Connection" Watch "JDBC Connection" New topic

JDBC Connection

satish bora

Joined: Jul 16, 2001
Posts: 18
Can somebody let me know the difference between following two ways of connection?
1. DriverManager.registerDriver((Driver)Class.forName(JDBCD).newInstance());
2. Class.forName(jdbcDriver);
Is there any specific reason when to use one or other.

ramalingam manonmani

Joined: Aug 07, 2001
Posts: 1
can i write odbc connectivity for javascripts.Should i need to write the code in java and then call that program in javascripts.Please suggest me.
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

I'll have a go at the second one (ramalingam manonmani) first: what you are probably looking for are JSPs and Servlets if you want to present database information in a web page...
Now to the initial question:
My preference has always been to use Class.forName("Driver class"). When the class is loaded, its static block (if it has one, and Drivers do have a static block) gets executed.
This allows the driver to register itself so that when you ask for a connection, the DriverManager can look to the registered Drivers and get one to return a Connection.
I'd imagine you could use the initial version when you had an instance of a driver already but did not load it or do not know how to load it yourself. Two ways in which this may occur is if the driver was streamed from some other site on the internet, or if the driver is not on your classpath and you loaded and instantiated it yourself... Pretty wierd but its possible.
As to the difference between Class.forName() and Class.forName().getInstance(), I've always prefered the initial version since it doesn't create a useless object. Then again, if you only ever creating one unused object in your code you're doing well so it isn't too much of a problem.
These are just thoughts so I wouldn't take them as fact but hope it helps anyway...
satish bora

Joined: Jul 16, 2001
Posts: 18
Thanks Dave.
I agree. Here's the link:
subject: JDBC Connection
It's not a secret anymore!