File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes JDBC and the fly likes What does the line Class.forName( Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "What does the line Class.forName("oracle.jdbc.OracleDriver"); actually do?" Watch "What does the line Class.forName("oracle.jdbc.OracleDriver"); actually do?" New topic
Author

What does the line Class.forName("oracle.jdbc.OracleDriver"); actually do?

Mark Scheid
Greenhorn

Joined: Oct 15, 2010
Posts: 2
What does the line -

Class.forName("oracle.jdbc.OracleDriver");

Actually do in the program? A snippet of my code follows.

*
*
*

public static void main(String[] args) {
try{

Class.forName("oracle.jdbc.OracleDriver");

String serverName = "oramwt1";
String portNumber = "4521";
String sid = "xxxxxxxxxxxxx";
String url = "jdbc: oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
String username = "xxx";
String password = "xxxxxxxxxxxxxxxxx";

Connection con = DriverManager.getConnection(url, username, password);
*
*
*

I appreciate the help and look forward to hearing from you.

Aelf
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

All JDBC Drivers are required to have a static code block that registers them with the DriverManager. Forcing the classloader to load the class will cause this code to run.


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39409
    
  28
And welcome to the Ranch
Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

All JDBC Drivers are required to have a static code block that registers them with the DriverManager.


You mean to say that this thing :



Save India From Corruption - Anna Hazare.
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

No.
Ravi Kiran Va
Ranch Hand

Joined: Apr 18, 2009
Posts: 2234

NO
so only this thing is sufficient
Class.forName("oracle.jdbc.OracleDriver");


and this piece of line of code is static method which will be responsible to establish the connection with the database. is this thing you ere refering .

I am asking because we generally use DataSource to get connections , but the above is a standard interview question . Thanks .
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

No, that method returns the Class object associated with the class of that name. To do this the class will have to be loaded at which point the static block in the Driver will be called.
 
Consider Paul's rocket mass heater.
 
subject: What does the line Class.forName("oracle.jdbc.OracleDriver"); actually do?