do i have to write Class.forname("com.mysql.jdbc.Driver") in every method in java?
While writing an application that interacts with a database the only way I can get it to work is if I write Class.forName("com.mysql.jdbc.Driver")
开发者_高级运维 in every method that interacts with the database.
Is this the only way to do it or is there a simpler way?
This line can't possibly work. jdbc:mysql://localhost/phone_book
is not a valid class name. You'll aways get an exception when executing this method.
If you mean Class.forname("com.mysql.jdbc.Driver")
, all it does is make sure the classloader loads the class. When the class is loaded, its static block is executed, and this static block registers the MySQL driver to the JDBC API. Doing it once is sufficient. Once a class is loaded, it's loaded. Loading it a second time won't change anything.
Invoking Class.forName(<jdbcDriverClass>)
serves to load the JDBC driver (that implements the java.sql.Driver
interface). Loading a JDBC driver class results in invocation of the static initializers within the Driver
and most, if not all all drivers invoke DriverManager.registerDriver(jdbcDriverInstance)
within the static initializer.
The pertinent method invocation serves the purpose of registering the JDBC driver with the DriverManager
, allowing for the DriverManager.getConnection
methods to return a connection to a database that is supported by the JDBC driver. Each JDBC driver recognizes only one/some JDBC URL connection format(s), and when you invoke DriverManager.getConnection(...)
, the DriverManager
class cycles through all the drivers registered, and only the driver that recognizes the connection URL format will return a connection.
Going by the above, Class.forname("jdbc:mysql://localhost/phone_book")
will make no sense in this context, as jdbc:mysql://localhost/phone_book
is not a JDBC driver class. Rather it is a connection URL format. Since you are interested in accessing a MySQL database instance, you should use the driver class of the MySQL Connector/J driver: Class.forName("com.mysql.jdbc.Driver")
. When you need to access the database instance, you ought to use the JDBC URL as: DriverManager.getConnection("jdbc:mysql://localhost/phone_book");
. You can pass in the user Id and password, using the three-parameter variant of the DriverManager.getConnection(...)
method.
精彩评论