问题描述
Class.forName("")与DriverManager.registerDriver()有区别吗?我是菜鸟希望说详细点
解决方案
解决方案二:
Class.forName表示加载一个类。加载一个类并没有实例化这个类,在加载类的同时会初始化这个类中所有的静态成员、静态块和静态方法。根据JDBC规范,Driver的实现类必须在静态块中使用DriverManager.registerDriver()方法将自己注册到驱动管理器中去。这也就是需要执行Class.forName的原因。当然了,加载JDBC驱动还有其他的方法,Class.forName只是其中之一。其他还有:*在系统属性将jdbc.drivers属性的值设为Driver的实现类名*实现JDBC4.0规范的驱动以后不再需要Class.forName或者是jdbc.drivers了,其采用ServiceProvider方式加载驱动。因为JDBC4规定JDBC的jar包必须在META-INF/services/java.sql.Driver文件中写出Driver的实现类。需要支持JDBC4新特性的功能需要在JDK6中运行,不过所有的JDBC驱动都是向下兼容的,因此JDBC4的驱动在JDK5及以下版本无法使用JDBC4中的新特性。MySQL支持JDBC4驱动版本是Connector/J5.0.0-beta及以后版本Oracle支持JDBC4驱动版本是ojdbc6.jarMSSQLServer支持JDBC4驱动版本是MicrosoftSQLServerJDBCDriver2.0
解决方案三:
下面这段代码是MySQLJDBC的Driver实现类的源代码,可以看一下其静态块中的内容:/*Copyright2002-2004MySQLAB,2008SunMicrosystemsAllrightsreserved.Useissubjecttolicenseterms.TheMySQLConnector/JislicensedunderthetermsoftheGPL,likemostMySQLConnectors.TherearespecialexceptionstothetermsandconditionsoftheGPLasitisappliedtothissoftware,seetheFLOSSLicenseExceptionavailableonmysql.com.Thisprogramisfreesoftware;youcanredistributeitand/ormodifyitunderthetermsoftheGNUGeneralPublicLicenseaspublishedbytheFreeSoftwareFoundation;version2oftheLicense.Thisprogramisdistributedinthehopethatitwillbeuseful,butWITHOUTANYWARRANTY;withouteventheimpliedwarrantyofMERCHANTABILITYorFITNESSFORAPARTICULARPURPOSE. SeetheGNUGeneralPublicLicenseformoredetails.YoushouldhavereceivedacopyoftheGNUGeneralPublicLicensealongwiththisprogram;ifnot,writetotheFreeSoftwareFoundation,Inc.,51FranklinSt,FifthFloor,Boston,MA02110-1301USA*/packagecom.mysql.jdbc;importjava.sql.SQLException;/***TheJavaSQLframeworkallowsformultipledatabasedrivers.Eachdriver*shouldsupplyaclassthatimplementstheDriverinterface**<p>*TheDriverManagerwilltrytoloadasmanydriversasitcanfindandthen*foranygivenconnectionrequest,itwillaskeachdriverinturntotryto*connecttothetargetURL.**<p>*ItisstronglyrecommendedthateachDriverclassshouldbesmalland*standalonesothattheDriverclasscanbeloadedandqueriedwithout*bringinginvastquantitiesofsupportingcode.**<p>*WhenaDriverclassisloaded,itshouldcreateaninstanceofitselfand*registeritwiththeDriverManager.Thismeansthatausercanloadand*registeradriverbydoingClass.forName("foo.bah.Driver")**@seeorg.gjt.mm.mysql.Connection*@seejava.sql.Driver*@authorMarkMatthews*@version$Id$*/publicclassDriverextendsNonRegisteringDriverimplementsjava.sql.Driver{//~Staticfields/initializers//---------------------------------------------////RegisterourselveswiththeDriverManager//static{try{java.sql.DriverManager.registerDriver(newDriver());}catch(SQLExceptionE){thrownewRuntimeException("Can'tregisterdriver!");}}//~Constructors//-----------------------------------------------------------/***ConstructanewdriverandregisteritwithDriverManager**@throwsSQLException*ifadatabaseerroroccurs.*/publicDriver()throwsSQLException{//RequiredforClass.forName().newInstance()}}
解决方案四:
刚才看了一下Oracle的ojdbc5.jar也支持JDBC4呵呵