Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Mark Scheid
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49763
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All JDBC Drivers are required to have a static code block that registers them with the DriverManager.


You mean to say that this thing :

 
Paul Sturrock
Bartender
Posts: 10336
Eclipse IDE Hibernate Java
 
Ravi Kiran Va
Ranch Hand
Posts: 2234
Eclipse IDE Firefox Browser Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic