Is Class.forName() mechanism needed? [duplicate]

╄→гoц情女王★ 提交于 2019-12-28 06:59:28

问题


Following code:

Class.forName(dbDriver); // "org.postgres.Driver" or "com.mysql.jdbc.Driver"

is / was necessary to open JDBC connection.

I have heard that it is no longer needed with modern JDBC drivers. However I can't remove it in my project, because I'm getting No suitable driver found exception. I am using postgresql-9.1-901.jdbc3.jar, Java7 and tomcat7.

When can I omit Class.forName(...) construct?


回答1:


Class.forName() is not needed since JDBC 4.0.

Here is an excerpt from Java Tutorials on JDBC.

In previous versions of JDBC, to obtain a connection, you first had to initialize your JDBC driver by calling the method Class.forName. This methods required an object of type java.sql.Driver. Each JDBC driver contains one or more classes that implements the interface java.sql.Driver. The drivers for Java DB are org.apache.derby.jdbc.EmbeddedDriver and org.apache.derby.jdbc.ClientDriver, and the one for MySQL Connector/J is com.mysql.jdbc.Driver. See the documentation of your DBMS driver to obtain the name of the class that implements the interface java.sql.Driver.

Any JDBC 4.0 drivers that are found in your class path are automatically loaded. (However, you must manually load any drivers prior to JDBC 4.0 with the method Class.forName.)



来源:https://stackoverflow.com/questions/33391496/is-class-forname-mechanism-needed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!