About Class.forName(...)
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Kamlakar_Bhopatkar
Posted On:   Saturday, June 16, 2007 09:08 PM

Normally when we write jdbc programs, the first two statements are : Class.forName("classname"); Connection con = DriverManager.getConnection("...."); But, why we have to use the class using forName? Why it cant be implemented as follows - import sun.jdbc....*; . . . JdbcOdbcDriver jd = new JdbcOdbcDriver(); Connection con = jd.getConnection("..."); . . . I mean, why they cannot be imported from proprietory packages like servlets? I mean HttpServlet and all are not part of JDK originally. But we import them from javax.servlet packet which is present in web server. So why jdbc drivers are loaded using   More>>

Normally when we write jdbc programs, the first two statements are :

Class.forName("classname");
Connection con = DriverManager.getConnection("....");


But, why we have to use the class using forName? Why it cant be implemented as follows -

import sun.jdbc....*;
.
.
.
JdbcOdbcDriver jd = new JdbcOdbcDriver();
Connection con = jd.getConnection("...");
.
.
.

I mean, why they cannot be imported from proprietory packages like servlets? I mean HttpServlet and all are not part of JDK originally. But we import them from javax.servlet packet which is present in web server.
So why jdbc drivers are loaded using Class.forName? Why they cant be used by creating objects?

Thanks in advance.

   <<Less

Re: About Class.forName(...)

Posted By:   WarnerJan_Veldhuis  
Posted On:   Sunday, June 17, 2007 05:37 AM

Class.forName() is used so that the static initializer block is run inside the Driver. This Driver then registers itself at the DriverManager. The URL that you hand to the DriverManager will contain a prefix like mysql, jdbc:odbc, etc. The DrvierManager will find which driver is suitable to handle this URL. Since you registered the Driver with Class.forName(), it's there to be found.



Happy coding.
About | Sitemap | Contact