Link to home
Start Free TrialLog in
Avatar of aquemini001
aquemini001

asked on

Explanation of "Class.forName" and "Connecton con = DriveManager.getConnecton"

Could someone explain to me the relavancy/pupose of the following two line of code, in the excerpt of code below?

Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection (url);



import java.sql.*;
public class P5 {
      public static void main (String args[]) {

            String url = "jdbc:odbc:P4";

            Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection (url);
Statement stmt = con.createStatement ();
String query = "SELECT ENO FROM Employee";
ResultSet rs = stmt.executeQuery (query);
while (rs.next())
{
        String eno = rs.getString("ENO");    
        System.out.println(eno);
}
      }
}
ASKER CERTIFIED SOLUTION
Avatar of sciuriware
sciuriware

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of sciuriware
sciuriware

Your second question: that's the same: choosing a database connection in the nick of time.
;JOOP!
ClassForName loads the java class with the specified name (so kinda... string TO class)
DriverManager uses that class to build a connectio to the db - the url is vendor-specific though...AFAIK

You might as well use the oracleDataSource directly, no need for a driverManager :P
Avatar of Mayank S
You might want to go through the JDBC tutorial to get a complete picture of what's happening:

http://java.sun.com/docs/books/tutorial/jdbc/
Daij-Djan is right -- Class.forName() simply causes the class to be loaded into the classloader. There is no compilation or anything, and in general this is not a mechanism for "selecting" a class.

As it happens, when JDBC driver classes load, they register themselves with JDBC's DriverManager. That way, DriverManager knows about the existence of your driver for your database and will use it when you later get a Connection.

This is the "old way" of obtaining a Connection. You ought to be using a DataSource. In a J2EE app,  you should configure the DataSource for your container and look it up using JNDI. Here is some more information, from the Tomcat documentation:
http://jakarta.apache.org/tomcat/tomcat-4.1-doc/jndi-datasource-examples-howto.html
Avatar of aquemini001

ASKER

thanks