Why Class.forName("driver class") ?

Hi,
whay we are using Class.forName("driver class"). why we dont import the driver package and access the required classes and methods?
for eg:
insead of calling
Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); ,can we use import com.microsoft.jdbc.sqlserver.*; ?
what is the use of DriverManager in this context? any connection between DriverManager and Class.forName() ?
expecting answers.

sure you can import the packages and use the classes directly but that defeats the whole purpose of pluggable drivers.
Class.forName causes the class to be loaded and as stated before that should cause the driver to register itself with the driver manager.
so then if you have a system where you are talking to several different database vendors then you don't have to worry about which is which as the DriverManager handles it for you.
the big pros that i have actually seen though for having this be pluggable and not hard-coded (with the exception of the URL although you can do this dynamically as well) is what happens if you switch databases. if you import the package and use fully named classes and you switch databases at some point (could be just an upgrade of the same vendor's database) you are screwed.
same problem could happen if you switch drivers for some reason.
at any rate if you use things properly and are careful then you should only ever have to change your URL the rest of the code is fine if you use the DriverManager and use the drivers dynamically otherwise...

Similar Messages

  • Why Class.forName is used to load the driver ?

    Hi all,
    Why Class.forName() is used to load the driver ?. Can I use any other method to load the driver safely ?.
    rgds
    Antony Paul

    That's still redundant. Sure, it works. Here are some equivalent forms:
        new MySqlDriver();
        DriverManager.registerDriver(new MySqlDriver());
        New LinkedList().add(new MySqlDriver());
        if (new MySqlDriver() == new MySqlDriver())
            System.out.println("department of redundancy department");
        Driver unusedVariable[] = new Driver[] { new MySqlDriver() };
        Class anotherUnusedVariable = MySqlDriver.class; // I'm not 100% sure this works
        new File(new MySqlDriver().toString());
        while (new MySqlDriver() == null)
        new Double(Math.sqrt(new MySqlDriver().toString().length()) / 42);

  • Why class defination and class implementaion separated in abap?

    hai experts,
                           i hav doubt why  class defination and class implementaion separated in abap. In know in  C++  its  possible
            but in JAVA its not possible . what is the main reson behind this concept in ABAP.
    thanks in adv.

    Hi Sree,
    As far as I feel, it's been done with a view of readability. As you know that ABAP  is very well modularized and organized programing language. When you define a local ABAP  Class, you define two seperate sections of it. You define the Class Definition and then you define the Implementations. This way you can really have a look at all the class definitions which are organized in the same section. Then you can have a look at the selected implementation.
    But if this hasn't been the scenario, then as developer looking at the complex classes would have made life hell for you. You can very well figure it out how good to keep things organized for later class maintainance and readability.
    Hope this would shed some light on your question.
    Thanks,
    Samantak.

  • Why wont my driver load?

    I quote the docs that come iwth the mysql driver: "The name of the class that implements java.sql.Driver in MySQL Connector/J is 'com.mysql.jdbc.Driver'. The 'org.gjt.mm.mysql.Driver' class name is also usable to remain backwards-compatible with MM.MySQL. You should use this class name when registering the driver, or when otherwise configuring software to use MySQL Connector/J."
    I'm compileing with this command:
    javac Select.java -classpath C:\;C:\mysql-connector-java-3.0.16-ga-bin.jar
    But it keeps saying "Failed to load mySQL driver." What's wrong? My hairs going grey :(
    import java.sql.*;
    public class Select {
         public static void main(String[] args){
         String url = "jdbc:mysql://database.dcs.aber.ac.uk/cha2";
         Connection con = null;
         try {
              String driver = "com.mysql.jdbc.Driver";
              Class.forName(driver).newInstance();
              catch ( Exception e ) {
                   System.out.println("Failed to load mySQL driver.");
                   return;
              try{
                   con=DriverManager.getConnection(url, "cha2", "mightymouse");
                   Statement select = con.createStatement();
                   ResultSet result = select.executeQuery("SELECT chaz FROM cha2");
                   System.out.println("Got result");
              catch (Exception e){
                   System.out.println("driver loaded(?), connection wrong(?)");
                   e.printStackTrace();
              finally {
                   if(con !=null) {
                        try{ con.close(); }
                        catch (Exception e) { e.printStackTrace(); }
    }

    I'm compileing with this command:
    javac Select.java -classpath
    C:\;C:\mysql-connector-java-3.0.16-ga-bin.jarI don't believe you need the JDBC JAR when you compile. You can compile like this:
    javac -classpath Select.java
    However, you absolutely need that JAR file when you run. Do it like this:
    java -classpath .;C:\mysql-connector-java-3.0.16-ga-bin.jar Select
    I'd recommend moving your Java source and that JAR file into a project-specific location (e.g, c:\DatabaseStuff). Create a source directory under that and put your .java code in there. Create a lib directory and put your 3rd party JARs in there. Learn Ant to automate your builds.
    %

  • What is the driver program & why we require driver program?

    What is the driver program & why we require driver program?

    In a Sapcript program the driver program plays an important role of calling the sapscript .
    Driver program contains Business Logic of the Program and rest all values are passed to scriprt which is called through driver.
    If it is based on output then standard forms called entry is called in the standard driver program .
    Please reward if useful.

  • Why start iCloud drive when Yosemite is not ready? Once accidental start iCloud drive, no downgrade option?

    When IOS8 is release there is a simple switch to start iCloud Drive.  It is a nightmare.  My iWork field can no longer be sync with my Mac and Mac Air.
    There is no downgrade method to resume the usual iCloud support.  Yosemite is not ready now.
    There should be a warning for anyone who may not know the link between iCloud drive and Yosemite.
    Why start iCloud drive when Yosemite is not ready for download?

    Give Apple feedback on this at http://www.apple.com/feedback
    Unfortunately the iOS 8 release was made fully functional even though some of the functions are not useable at this time.  That should have been clearer so the user knew not to activate a function that would not work fully.

  • Why class.forName to load driver

    hi all,
    as most of the times the loading of jdbc driver is carried out
    by using the function class.forName, Why so ?
    as i tryied with creating the object of the driver class like
    Object driver = new <JDBC DRIVER>;and the code worked fine
    so is there any difference in the two methods of loading the
    drivers ?
    if not wot is the use of method class.forname ?
    thanx

    That 's fine, but what if you change database back end in near future.
    I will define a property and used class.forName ("read property").
    In your case, you have to change the code about loading the JDBC driver as well.
    Using std. JDBC API functionality and loading driver dynamically, leaves some of the part of the code that are not a candidate for a change in case back-end DB is changed.
    BS

  • 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.

  • 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

  • Why Class characteristics req in QM

    Hi QM Gurus,
    I have inspection plan with MIC it is working very well.
    But some of  them told you can use class characteristics with MIC.
    My question is.
    1. What is the use of class characteristics?
    2. why it is assign to MIC.
    Please clarify....
    Regards,
    Babu.S

    Dear Singh,
    >1. What is the use of class characteristics?
    It migrates the results recorded to the Batch Class.
    >2. why it is assign to MIC.
    Class Characteristic is assign to...
    - 1. Batch Class, and this batch class is assigned to Material
    - 2. With reference to this Class Characteristic, an MIC is created, and this MIC is getting assigned to the Inspection Plan/ Material Specification of the Material.
    - Now when the RR is done for these MIC, in the inspection lot for the Material, the Values of Result, Migrates to the Batch, in the Batch Class.
    To test the scenario
    - Create a Characteristic (CT04)
    - Create a Batch Class (CL02)
    - Assign the Characteristic to the Batch Class.
    - Assign the Batch Class to Material.
    - Create an MIC, using the Characteristic (QS21)
    - Assign the MIC to the Inspection Plan (QP01)/ Material Specification (QS61), of the Material.
    - Create an Inspection Lot for the Material, have new Batch.
    - Perform RR and UD.
    - Now go to MMBE,MM02,BMBC,MSC3N, and check the value of the Result is Migrated here in the Batch, under Batch Class.
    NOTE:-. It will not work if the material is not Batch Managed.
    Let me know the progress.
    Have Happy Week End!!!!!!!!
    Regards,
    Shyamal

  • Why class builder allows to develop abstract final class ? What is the use of such class in ABAP?

    I am new to ABAP. I tried creating abstract class and found that class builder allows development of abstract final class. What is the use of such class in ABAP?

    Hi,
    Does not compile:
    This one do:
    Inheritance:
    Regards.

  • Question on why Class is not being called by POST Form action

    Hello I am trying to use JavaMail and send an email to myself for a test through a JSP form. I have this line in my jsp code
    <form name="emailSendForm" action="servlet/EmailServlet/NewEmail.class" METHOD="POST" >Then this is my doPost method
    public void doPost (HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
      System.out.println("Hello we are in the New Mail");
      HttpSession session = request.getSession (false);However, nothing happens when I hit my submit button. Even my system.out message is not even appearing. I am missing a piece of code? Thanks

    Where are you storing the .class file? I'm getting the idea that you are not storing it inside the WEB-INF/classes directory but in the web root like you would a JSP.
    Servlets don't work that way. I'll illustrate an example setup.
    Say I have a servlet called NewEmail and it is in the package servlet.email.
    step 1: make sure the servlet .class file is stored in the proper directory. This is webapproot/WEB-INF/classes/servlet/email/NewEmail.class. The directory structure inside the WEB-INF/classes directory matches the package of the servlet (this directory is part of the classpath of your web application).
    step 2: define the servlet in the WEB-INF/web.xml file of your web application. If you don't do this you cannot invoke the servlet.
    <servlet>
    <servlet-name>NewEmail</servlet-name>
    <servlet-class>servlet.email.NewEmail</servlet>
    </servlet>
    <servlet-mapping>
    <servlet-name>NewEmail</servlet-name>
    <url-pattern>/NewEmail</url-pattern>
    </servlet-mapping>The url-pattern defines how you will be invoking your servlet through the web. NewEmail means that you can submit to "NewEmail" or call the servlet as http://yourwebsite.com/NewEmail.
    Step 3: put the right URL in your form
    <form name="emailSendForm" action="NewEmail" method="post">
    </form>Again, check that the action attribute matches the url-pattern without the slash in front of it.
    That should do it! Unless I made a typo somewhere of course.
    Note by the way that System.out.println is NOT going to send anything to the browser, but most likely to a logfile kept by the webserver. You need to send data using the response object to make it appear in the browser.

  • Why class name must be same as its file name?

    just curious

    http://forum.java.sun.com/thread.jspa?forumID=54&threadID=613486
    http://forum.java.sun.com/thread.jspa?forumID=256&threadID=452360
    http://forum.java.sun.com/thread.jspa?forumID=513&threadID=516940

  • Why do USB drives plugged into USB hubs make my Mac Book Pro (Retina late 2013) wake from sleep?

    I have 2 x USB hubs, a Logitech USB 2.0 hub and a Broway USB 3.0 hub. Tested both and both seem to be the cause of my late 2013 Mac Book Pro waking from sleep. I ran syslog to find out why (syslog |grep -i "Wake reason") and the reason I got back was "kernel[0] <Notice>: Wake reason: XHC1" - this means nothing to me, but it didn't take too much mucking about to hunt the problem down and figure out it was the USB hub with any USB drive attached. If the drive is attached directly to the computer. No problem, computer sleeps fine.
    This was a problem I encountered (and never solved) with OSX 10.6.8, a 2008 Macbook Pro the same Logitech USB 2.0 hub, but with different drives. I put the problem down to a bug that never got solved in an old system. But I am simply AMAZED after my update to a new MBP and new system that it is still about almost 6 years, a dozen MBP's and 4 systems later.
    The other problem is that not only does the USB drive/ USB hub combo wake the computer it also loses the drive upon sleep and mounts it again upon wake. Then repeats this process every couple of minutes. And it obviously doesn't eject the drives properly because each time I return to the computer after I put it to sleep or let it go to sleep I get a giant list of "Disk Not Ejected Properly" notifications about it. Which I'm guessing could eventually cause some file damage.
    I've tried combinations of different drives, different hubs (a Belkin and a no-name Chinese brand 2.0 hub) and the problem persists. Is there a solve to this problem? I'm surprised to see so little posts on forums about this. Am I just unlucky and got another combination of faulty/problematic hardware, or is this a real problem that exists for everyone? If not I would love to know if people have found winning combos of USB hubs and drives. But if it is, then it HAS to be solved.
    If you have a Macbook Pro, then you are limited to 2 USB outlets, this is obviously a bare minimum and I would say that 95% of people using their laptop computer in the office or at home have a hub, and very likely a USB drive attached to it. I know actual Apple reps don't really pay much attention to the community support posts, but I've got 6 months worth of Applecare left and would like suggestions about how to get Apple's attention about this problem.
    BTW Jettison (a 3rd party app that ejects drives properly before sleep) is not a solve. It is a 3rd party app that tries to fill a hole in a broken system. I don't want to eject my drive upon sleep, I want it to got the **** to sleep.

    Is there a pattern to the time of day or other detail that may be
    traced back to a OS X system cause of this odd phenomenon?
    Are there any copies of system files on any of the attached USB
    external drives? Any libraries, such as iTunes, iPhoto, etc?
    Once the drives are indexed by Spotlight, are their permissions
    ignored by the OS X? Content, if neutral, should not affect the
    wake or sleep cycle; especially if they're ignored by the OS X.
    Could there be a bad cable or other component? If so that would
    be a difficult process of elimination to detect it. Usually replacing
    most suspect components in the USB stream (external to Macs)
    is a rote way to mechanically test that idea; & not 100% sure.
    Does the equipment all have a good ground to the utility or house
    electrical field? An intermittent ground may affect more than sleep.
    Hard to say at this point. Maybe a late-night talk radio guru on
    remote viewing could peer into your situation and sleuth it out?
    Sorry to have run out of ideas, but the process must be electrical
    & mechanical to some extent. - Or perhaps odd software inspired.
    Do you have any phone-home spyware items inside, just jumping
    at the chance to spill your information? Little Snitch may help.
    PS: Perhaps the computer needs to go into Apple & have a genius
    or product specialist at AASP test the unit thoroughly... BlueTooth?
    see:
    https://www.google.com/?gws_rd=ssl#q=Wake+reason:+XHC1
    Good luck & happy computing!
    edited 2x

  • Any idea why my desktop drive name changed to '\

    Hi.
    Just sat down to do some work for the first time in two days and noticed that an external drive on my iMac and a desktop folder have had their names changed.  The drive changed to '\ and the folder changed to \
    I found my 3-year-old noodling on the keyboard for a few seconds earlier in the day, but don't think that's it.  The two new names seem ominously similar and suspicious.  The folder was no problem -- I just created a new folder with the old name, copied my files to it, and then trashed the one with the changed name.  The hard drive will not let me change its name, however.  I can click on the name field, but when I start typing, it tabs to the next item on the desktop.
    I restarted, ran Disk Utility to verify the drive in question, and repaired permissions on the internal drive.  I do think I have one tiny bad spot on this external disk, but it's been working fine otherwise and I have it backed up.  But regardless, this wouldn't explain why a totally unrelated folder on my desktop suffered a similar fate.
    Any ideas what caused this, whether I can change the name back, or if it's going to cause problems down the line if I can't? 
    Thank you.

    Do you have children or a cat? I found the same thing after my grandson visited not long after he reached the "mobile" stage. A few minutes banging on teh keyboard of my wife's iMac left the hard drive with an odd character for a name.
    Cats are more computer-literate that many people think. When they walk across the keyboard, they seem to know exactly the right keystrokes to make you computer do odd things--if you are lucky. If you are not lucky, cats know how to leave remnants of meals past of worse on a keyboard.

Maybe you are looking for

  • Is it possible to mail the data in excel format in data tabs?

    Hi all, I need a few clarification . We all know report data can be mailed in excel format. But my excel is having 4 tabs of data. Is that can also be mailed if so can you please guide... Regards sas

  • Adobe Flash Player 11 runs slowly in FF 14

    Currently using FF 14 (release channel) with Flash Player 11 (updated today, 7/21/12). Flash objects, such as Facebook games, run slow/choppy to the point where it looks like a collection of tiles updating over the course of a few seconds. I have del

  • I can't delete my Mail on my Macbook Pro

    I have tried to delete my "all mail" mailbox of 1747 messages, but they keep re-entering the mailbox.

  • Changing hostname for embeded OC4j

    I have a web-application that computes a hash number based on the server name in which the app is running. Needless to say, running OC4J from JDeveloper in debug mode creates a url like: http://<host_ip>:<port>/app/index.jsp. I need to make it launch

  • Printing sapscript label using zebra printer

    Hi, Can anybody please help me regarding "printing sapscript label using zebra printer"? i hav set the following print default settings in the transaction mb90: output device : NO01 device type: YZZX_ZEB but when i try to print ,i am getting error me