Use of Class.forName() in JDBC

Hi,
I know that in JDBC "Class.forName()" is used to load the JDBC driver classes.
Is this the only purpose of "Class.forName()" method specially in JDBC?

thanks much..
ok so. calling the Class.forName automatically
creates an instance of a driver and registers it with
the DriverManager.more or less
When we use the string / string buffer class we don�t
need to explicitly load the classes exist in
�java.Lang� package.they get loaded - as do all classes - when your code first tries to use them.
But to get the JDBC connection, we need to insert the
code
�Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");�..
please clear my confusion.it's really because the JDBC driver might not be known at compile-time. Class.forName allows us to load classes at runtime we didn't know about at compile-time. you could just as easily load java.lang.String using the above method, but since the method takes a string, the class will be loaded already! you could also just as easily do
import sun.jdbc.odbc.JdbcOdbcDriver;
new JdbcOdbcDriver();that would also load the class. but that then couples your code to that particular driver. generally, in real applications, the driver classname would come from a config file, rather than hard-coded in the application. Class.forName() gives us that flexibility

Similar Messages

  • Strange use of Class.forName() in JDBC

    The following is the classical code to retreive data from a database via JDBC
            Connection con;
            Statement stmt;
            String querystring;
            String parametervalue = "";
            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch(java.lang.ClassNotFoundException e) {
                System.err.print("ClassNotFoundException: ");
                System.err.println(e.getMessage());
            try {
                con = DriverManager.getConnection(dburl);
                stmt = con.createStatement();
                querystring = "select ParameterValue from Profile ";
                ResultSet rs = stmt.executeQuery(querystring);
                if(rs.next()) parametervalue = rs.getString("ParameterValue");
                rs.close();
                stmt.close();
                con.close();
            } catch(SQLException ex) {
                System.err.println("-----SQLException-----");
                System.err.println("SQLState:  " + ex.getSQLState());
                System.err.println("Message:  " + ex.getMessage());
                System.err.println("Vendor:  " + ex.getErrorCode());
            return parametervalue;         but the use of Class.forName("com.mysql.jdbc.Driver") is strange. it doesn't need to get the returned Class
    like: Class t = Class.forName("com.mysql.jdbc.Driver"),and the DriverManager knows which driver to use!
    Any one can give an explanation?
    thanks

    * It's more natural from an OO perspective for me to
    tell the manager about the classes it manages thanfor
    the classes to know about the manager and tell it
    about themselves.
    No.Hmmm. Care to elaborate? I don't have anything to really back this up, but it seems to me that a class shouldn't have to know too much about the context in which it is used. Drivers shouldn't have to know that there is a DriverManager that will be managing them. IMHO.
    I thought of another reason: Since you're doing either the Class.forName or the DriverManger.register in the client, no work is saved there either way (as you said, register is just as easy to call as forName), but using Class.forName adds extra complexity in the Drivers. I guess this is probably the same as, or very close to "protected users from themselves" though.
    If the forName() doesn't happen somewhere then the
    class doesn't get loaded.I'm thinking more along the lines of classes getting loaded in a different area of the code than the DB client. Some kind of plugin-type thing maybe, where the plugin manager automatically loads all the classes in a certain classpath-like set of diretories and jars, without knowing or caring what each one is (DB plugin, graphics plugin, encryption plugin, messaging plugin, etc.) or how it's used. The DB client then wouldn't know which specific driver(s) it has available, only that whatever was visible to the plugin manager will be loaded, and some subset of that could be DB drivers.
    In this situation, it's not appropriate for the plugin manager to register the drivers, since it doesn't know anything about JDBC, and it's not appropriate for the DB client to register them, since it doesn't know what classes the plugin manager loaded.
    I suppose the DB client could query the plugin manager for all its loaded plugins, then check if each one implements Driver, and if it does, then register it. Or maybe the plugin manager could even store a map whose keys are interface Class objects or interface names and whose values are lists of the plugins that implement that interface.
    I don't know if this scenario is used, or is even good design, but it doesn't seem too farfetched. This is the kind of situation where it seems to me the driver is the one in the best position to know both a) he has been loaded and b) he needs to be registered.

  • Error class not found with Class.forName("oracle.jdbc.driver.OracleDriver")

    sorry Got the solution...!!!!
    Hi
    I am trying to connect to oracle database on the server, oracle client installed on working m/c, I have placed classes111.zip (from oracle 8) in jdk1.1.8demojrelibext folder and I have set the classpath to the ext folder. The code
    try
    Class.forName("oracle.jdbc.driver.OracleDriver");
    catch(Exception e)
    when I run this code , error as
    [[ java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver ]]
    Please reply what are settings I should to to load this oracle driver,
    Thanks
    Mayank
    Message was edited by:
    user560333

    I currently have this same problem. How did you solve yours see my post Cant find suitable driver.

  • Why Class.forName?...

    I'm trying to understand the use of Class.forName in JDBC programing. �What is the really goal for this class?
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    } catch(ClassNotFoundException ex){
    // something
    Regards.

    I'm trying to understand the use of Class.forName in
    JDBC programing. �What is the really goal for this
    class?There are two implied questions...
    -What does it do?
    1. The class is loaded. All classes are loaded this way but normally the compiler does the work for you.
    2. When a class is loaded, if there are any 'static initializers' in the class then those are run. Again true for any class when it is loaded.
    3. JDBC drivers have a static initializer which registers the driver with the JDBC driver manager. See the DriverManager.registerDriver(Driver driver) method and the JDBC spec for more specific info.
    -Why it is done this way?
    As a guess because the original JDBC implementor(s) just found out about static initializers and thought they were 'cool'. It would be just as easy and more meaningful to do it using a different methodology.

  • Forbit use of method forName of Class

    I have some JAVA applications running in iPlanet Application Server (iAS). I need that the connection to database was only by the pool of iAS and nobody can use:
    Class.forName("oracle.jdbc.driver.OracleDriver"); to connect to DB.
    How can forbit use of method forName of Class?

    You can't.

  • Database connectivity without using Class.forName()

    Hi,
    Can anyone please tell how we can connect to a database without in java without using the Class.forName() method , and then how the database driver gets loaded.
    Regards,
    Tanmoy

    Hi,
    I recently wrote code that connects to a database without using Class.forName() in order to be compatible with Microsoft's JVM. I read about it here:
    http://www.idssoftware.com/faq-e.html#E1
    Basically, you create a new Driver object and use its connect method.
    Here's what my particular code ended up being:
    String url = "jdbc:mysql://localhost:3306/test?user=root&password=mypass";
    Driver drv = new org.gjt.mm.mysql.Driver();
    Connection con = drv.connect(url,null);

  • Why can't i use class.forName(str) ?

    Heys all i have this piece of code which is working fine:
    *try {*
    java.lang.Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    *} catch (java.lang.ClassNotFoundException e) {*
    now the problem is that i was under the impression that i could use class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); but it wouldn't compile. does anyone know why is this so?

    Class.forName() says "call the static method forName() that is defined in java.lang.Class". It returns a reference to an instance of java.lang.Class.
    SomeClass.class is known as a class literal. It is not a member, not a field, not a method. It evaluates to a reference to an instance of java.lang.Class.
    You cannot do class.something().
    Edited by: jverd on Oct 26, 2010 9:46 AM

  • Class.forName(driver) = ClassNotFoundException

    hy all!
    the following statements causes an error:
    Class.forName("oracle.jdbc.driver.OracleDriver");I printed some informations about the exception:
    Errorcause: null
    Errormessage: oracle.jdbc.driver.OracleDriver
    Class: class java.lang.ClassNotFoundException
    StackTrace: [Ljava.lang.StackTraceElement;@16
    (I�m using JDeveloper)
    what do I have to do?? Is something missing on my harddrive??
    can you guide me?
    thanks!
    lenaz

    oracle jdeveloper build 10.1.2
    1. select the project then right click
    2. select the project properties
    3. expand the Profiles and select the libraries
    4. select the Oracle JDBC then click >
    5. click ok

  • Class.forName Failure

    I have a simple app (written in Eclipse), which has the following line:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    classes12.zip is in the classpath. The app runs from Eclipse; another app in another project uses the same Class.forName(XXX) and it runs outside of Eclipse; it's JSPs and sevlets running with Tomcat. This app is just a pure java application. If I use the classpath parameter when invoking the jar file. same result. Class not found error.

    RonNYC wrote:
    I have a simple app (written in Eclipse), which has the following line:
    Class.forName("oracle.jdbc.driver.OracleDriver");
    classes12.zip is in the classpath.Quite clearly it's not.
    The app runs from Eclipse;Doesn't matter. Eclipse doesn't use your classpath, it sets its own.
    another app in another project uses the same Class.forName(XXX) and it runs outside of Eclipse; it's JSPs and sevlets running with Tomcat.Which also sets its own classpath.
    This app is just a pure java application. If I use the classpath parameter when invoking the jar file. same result. Class not found error.Which clearly does not have its classpath correctly set.
    Why are you using an ancient driver anyway? Or are you using Oracle 8?

  • Applet - Class.forName..

    I have an applet which is loading fine but my combo boxes aren't getting populated - I'm getting "Failed to load JBDC/ODBC driver" because of the following:
    try{
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    catch(Exception e){
    System.out.println("Failed to load JBDC/ODBC driver");
    Any ideas?
    Jacintha

    What are you actually trying to do? Are you connecting through a Servlet/JSP or is it a standalone applet? Seems like you are using Windows. Use ODBC Datasources in the Control Panel to set a DSN. Which database are you using? Which Platform are you working on and what is the objective of your applet?
    I have an application and when you click a particular button on a jsp - you are directed to the html file that loads the applet. I'm using an Oracle database. When the applet loads ( a swing applet) the buttons etc comes up but the combo boxes are not populated - should be populated from the database - I have been looking through this forum and some have mentioned to sign the applet - I am in the process of doing this - I don't know if you know anything about this. I have got as far as signing the jar file and exporting the public key certificate - but now it goes into details about the code receiver which I'm getting puzzled about. I am using the following site: http://java.sun.com/docs/books/tutorial/security1.2/toolsign/index.html. I don't know what direction to go now!

  • Difference between "new classname()" and  class.forName("...")?

    Hi,
    Please clarify me : What is the difference between the instnce creation by using new operator *( new ClassName())* and instance creation using class.forName("fully Qualified Name");
    thanks
    Gaurav

    The compiler can tell you whether new ClassName() will be valid. For the other, you have to wait until runtime to know for sure.
    new ClassName(...) can be invoked with arguments, and you provide them directly and simply. If you want to reflectively create an instance using a constructor that takes arguments, it's a more convoluted process.
    Using new, you know which checked exceptions can be thrown and you catch them directly. Using reflection, you have to catch some other exception and unravel its cause.
    You can use reflection (Class.forName and its more complicated cousins) when you don't know the classname at compile time.You can't do this with new.
    Don't use reflection unless you have to. It's more complex, somewhat less performant, and it denies you certain compile time checks.

  • Use "external" classes as plugins

    hi everyone :-)
    i have an application which offers some plugins to the user.
    now the thing is: the plugins shouldn't be included into my JAR-file, the should be in an external folderstructure outside of the JAR.
    when i use the Class.forName(...)-method, i cannot access the external classes... even if i add the package-path of them (i.e. "pluginsp.plugin1.Plugin1")
    has anyone an idea how to solve?
    thx a lot & regards
    manu

    OSGi is pretty bulky and is a spec. Eclipse is built around OSGi. Perhaps the better implementation is OSCAR, an open-source implementation of OSGi that is more a stand-alone plugin engine like my Platonos Pluginengine is.
    Depends on what you want. Small, fast, easy to work with and get up in about 5 mins? Go for mine. If you need something a little more industry standards based but is more complicated to work with and quite a bit bulkier in terms of the library size, go for OSCAR. I am not slamming OSCAR or OSGi. OSCAR is very slick, and OSGi is a great initiative. Just offering another solution that may work out better.

  • Class.forName() debunked

    This issue is about: Dynamic loading and Inheritance.
    Debugging an odd ClassNotFoundException in a J2EE Application, I was involved investigating deeply Class.ForName(). This method - namely the version with only the class name as parameter - is used inside xsdbeans.jar, an optiopnal library, shipped with IBM WebSphere 5.x. Moving the jar from the EAR classloader to the server runtime classloader caused weird behavior on my app.
    I try to simplify the core question:
    Suppose class E extends B. Base class B declares an instance method, dynLoad(String name) that uses internally Class.forName(String name).
    Say 'e' an instance of E. Invoking e.dynLoad("Foo"), Class.forName("Foo") should use the ClassLoader of current class. But which is the 'current class': E or B? Is it the class of current object (E) or the declaring superclass (B)?
    My instinctive answer was: E. But my J2EE app was behaving as the current class was B. Indeed E and B may be defined by different classloaders, and this makes a big difference.
    A rapid lookup at Sun's docs confirmed my first hypothesis:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String)
    > Returns the Class object associated with the class or interface with the given string name.
    Invoking this method is equivalent to:
    Class.forName(className, true, currentLoader)
    where currentLoader denotes the defining class loader of the current class.
    ok, this is a little misleading, but going on:
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Class.html#forName(java.lang.String,%20boolean,%20java.lang.ClassLoader)
    > For example, in an instance method the expression:
    >
    Class.forName("Foo")
    is equivalent to:
    Class.forName("Foo", true, this.getClass().getClassLoader())
    Not equivocal. The current class is the class of current object, no matter (apparently) if the instance method is declared in a superclass.
    Right? Wrong. Here a minimal counter-example:
    //-- B.java
    import java.net.*;
    public class B {
        public void dynLoad(String name) throws Exception {
            System.out.println(getClass().getSuperclass()
                + " defining classloader is: "
                + getClass().getSuperclass().getClassLoader());
            System.out.println(getClass()
                + " defining classloader is: "
                + getClass().getClassLoader());
            System.out.println("\n1) Class.forName(\""+name+"\");");
            // Loading with 'currentLoader'
            Class.forName(name)
                .newInstance();
            System.out.println("\n2) Class.forName(\""+name
                +"\", true, this.getClass().getClassLoader());");
            // This should be equivalent (by Sun J2SE API spec)
            Class.forName(name, true, this.getClass().getClassLoader())
                .newInstance();
        public static void main(String[] args) {
            ClassLoader syscl = ClassLoader.getSystemClassLoader();
            if (!URLClassLoader.class.isInstance(syscl)) {
                System.err.println("Cannot continue the trick.");
                System.exit(1);
            URL[] urls = ((URLClassLoader)syscl).getURLs();
            // Yet Another ClassLoader
            URLClassLoader yacl = new URLClassLoader(urls) {
                // Force Parent-last delegation policy to assure
                // demanded classes are defined by _this_ classloader
                public Class loadClass(String name)
                    throws ClassNotFoundException {
                    Class c = findLoadedClass(name);
                    if (c == null) {
                        try {
                            // Simulate no visibility to base class to assure
                            // it is _not_ defined by this classloader too
                            if (name.equalsIgnoreCase("B")) {
                                throw new ClassNotFoundException();
                            c = findClass(name);
                        } catch (ClassNotFoundException e) {
                            c = getParent().loadClass(name);
                    return c;
            try {
                // Loading class E with a different classloader
                Class c = yacl.loadClass("E");
                c.getMethod("dynLoad", new Class[]{String.class})
                    .invoke(c.newInstance(), new Object[]{"Foo"});
            } catch (Exception ex) {
                ex.printStackTrace();
                System.exit(1);
    //-- E.java
    public class E extends B {
    //-- Foo.java
    public class Foo {
      public Foo() {
        System.out.println(getClass()
          + " defining classloader is: "
          + getClass().getClassLoader());
    }Running above B.main() produce the following output on Sun JDK 1.3, 1.4.2, 1.5:
    > class B defining classloader is: sun.misc.Launcher$AppClassLoader@3d200480
    class E defining classloader is: B$1@3d2c0480
    1) Class.forName("Foo");
    class Foo defining classloader is: sun.misc.Launcher$AppClassLoader@3d200480
    2) Class.forName("Foo", true, this.getClass().getClassLoader());
    class Foo defining classloader is: B$1@3d2c0480
    The evidence is that classloader used is not the same. in the case 1) it uses the classloader of superclass B. Hence the two form of Class.forName() invocation are not equivalent, as stated in Sun documentation.
    Disclosure
    The evidence is confirmed and explained looking at Sun's implementation of java.lang.Class.java and java.lang.ClassLoader.java: finally the Class.forName(String name) relies on sun.reflect.Reflection.getCallerClass(int) to find the famous 'current class' mentioned in the javadocs. This undocumented method returns the i-th caller class of current stack frames; each stack frame represents a method invocation coupled with its declaring class.
    I wonder why in Sun docs this poorly explained issue was remaining immutable from 1.3 to date. Furthermore: which was the intended behavior? Another reason to the long said "Class.forName() is evil..." or am I missing something?
    regards, Lorenzo

    Of course, it comes down to the question: What is the current class?
    Not something well defined. You are looking for this.getClass(), it's taking the class at compile time. If it went your way, woundn't that create an inconsistency in forName in static vs instance contexts?
    Actually I think the static approach is more natural, because it means that forName behaves the way that resolving external references work. Your way would also go against the spirit of Java security policies which requires references down the classloader chain something to be treated with suspision.
    The mechanism intended, I think, for these situations is the contextClassLoader property of Thread. When executing plugin type code the contextClassLoader should be set to the ClassLoader that loaded the plugin, and any references to resources or dynamic class loads from the plugin should be made using the contextClassLoader. This enables your shared library code to access classes and resources on behalf of the plugin code with access to classes and resources inside the plugin.
    Thus, if you write library code or other container stuff likely to be called from a plugin you should probably always use:
    Class cls = Thread.currentThread().getContextClassLoader().loadClass("foo");

  • Need a clear explanation for class.forName()

    Class.forName(sun.jdbc.odbc.JdbcOdbcDriver);
    Connection conn = DriverManager.getConnection("aadsn","xxxxx","xxxx");
    actually what it does behind the scene.

    (Copied from http://forum.java.sun.com/thread.jsp?forum=48&thread=471358)
    Class.forName() loads the given class. In itself, that isn't interesting. The beef lies in that loading a class executes any static blocks in that class.
    If you had the source to com.mysql.jdbc.Driver, it would probably start something like:
    public class Driver
        static {
            Driver driver_object = new Driver();
            java.sql.DriverManager.registerDriver(driver_object);
    }The static block does the actual work of registering the driver. Class.forName() is really just a bit of a hack to get that static block executed.
    The newInstance() call is customary because there is an old rumor that some buggy JDBC driver somewhere is missing the static block, and has the registerDriver() call in a Driver() object constructor instead. A belt and suspenders kind of thing.
    If you want to see real life examples of that static block, google around for open source JDBC drivers.

  • Class.forname:Oracle "Error" cannot resolve Sysmbol

    I am stil new in java can you pls help me with this error. I have a main class
    i am trying to make an oracle connection but i get this error when I RUN THE CLASS IN DOS
    Try.java [61:1] cannot resolve symbol
    symbol : method forName (java.lang.String)
    location: class Class
    Class.forName("oracle.jdbc.driver.OracleDriver");

    very simple... add classes12.jar file to classpath

Maybe you are looking for

  • Methods to do increasing in java coding

    may i know how to do a selective code to do increasing in java code? like : i got numbers 20, 30, 20 ,20 IT IS BEFORE I ENTERED ANY NUMBERS IN !! uniqueNumber 0 numberOfuniqueNumbers 0 occurrences 0 IF i enter 20 into the system THEN uniqueNumber wil

  • Page item parameters with comma passed incorrectly

    using APEX 3.0, I set up a page with a report with a link column. On the link section of the column, I have set up two items to be set on the following page. However, one of those two values has commas in it, and is not passed correctly. It actually

  • Mail signatures seen as attachments in PC's.

    Hi there. I am using Mail for a .Mac, Hotmail, Gmail and a company account and when I create a signature it is seen as an attachment on Windows machines. Is it a Mac thing, and Intel thing (since the MacBook is a fairly 'green' machine so far) or jus

  • Paypal Buttons Malfunctioning

    I have set up a trial site using Muse that has Paypal Buy Now buttons to sell a product. I want to sell the product in different countries and so I have created different web pages for each country. On each of these pages is a Paypal Buy Now button w

  • Spl_autoload_register not working in production

    I have a WampServer on my dev machine and use a LAMP stack for production (L = Ubuntu 12.04 LTS). PHP version is 5.3.10-1 on LAMP and 5.4.3 on WampServer. As far as I can tell the spl_autoload_register function should work on php 5.3 + and so should