I have recently started jdbc nd now i am confused that what is the real purpose of Class.forname() method??
Also what is the diff. between Class.forname() and DriverManager.registerDriver()??
plz reply soon

Recommended Answers

All 7 Replies

First, have you read the API doc for those two methods?

How have you seen them used? Do you have a code sample?

registerDriver is the "old" form. The driver classes are to do that themselves when loaded (the reason for the Class.forName() call). In fact, in Java 6 and later, if the driver implements the Services interface (which it must do to qualify as a valid Java 6 JDBC driver (JDBC version 4.0, I believe) not Type 4, there is a difference between the JDBC version and the Type), you don't have to do either of those.

What package is the Services interface in. I can't find it in my API doc

It's not really an interface. See this, section 9.2.1. It is actually the jdbc.services system property (which is can, of course, also be set in the control panel, and in JNLP and jws configurations). I swear I have read somewhere that when the manifest is set up properly that you don't even need to set that property (which is what I meant by the Services interface), but I can't, for the life of me, find it now. Maybe it was only in relationtion to JEE 6 capable containers.

I swear I have read somewhere that when the manifest is set up properly that you don't even need to set that property (which is what I meant by the Services interface), but I can't, for the life of me, find it now. Maybe it was only in relationtion to JEE 6 capable containers.

You are probably talking about the ServiceLoader class which was introduced in Mustang. Derby uses this for loading and registering its client drivers whenever you have the derby-client.jar in your classpath.

Could be.

Back to the OPs question.
The Class.forName("driver class name") causes the class to be read and the static block in it to execute.
The static block creates an instance of the Driver class and calls:
DriverManager.registerDriver(driverRef);
to register it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.