This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
The first step to using a database in java is a call to: Class.forName("driver name"); or Class.forName("driver name").newInstance(); Now, my understanding is that this is so that a static block in the driver can register the driver so that a call to DriverManager.getConnection knows which driver to call without the user having to hard code it. My question is: is there a difference between the two calls? I tend to favour the first one since there's no point instantiating an object if you aren't going to use it, but am I missing something? Many of the sample JDBC code I see flying around uses the second version. On a related note, it would appear that the above code would only allow a single database at a time. If you want multiple databases is it acceptable to use... Driver oracleDriver = (Driver)Class.forName("oracle driver").newInstance(); Driver oracleDriver = (Driver)Class.forName("jdbc-odbc").newInstance(); and then obtain Connections individually? Just thinking out loud. Dave.
According to JAVA API http://java.sun.com/j2se/1.3/docs/api/index.html Instances of the class Class represent classes and interfaces in a running Java application. Class has no public constructor. Instead Class objects are constructed automatically by the Java Virtual Machine as classes are loaded and by calls to the defineClass method in the class loader. The static method forName(String className) returns the Class object associated with the class or interface with the given string name. The method newInstance() creates a new instance of the class represented by this Class object. So we see that there is no use to using the newInstance() method since we just have to load the JDBC driver which is already being accomplished by calling the forName() static method of the Class class.