该java.sql.DriverManager中的类管理应用程序中的JDBC驱动程序。此类维护所需的驱动程序列表,并在初始化时加载它们。
因此,您需要在使用前注册驱动程序类。但是,每个应用程序只需要执行一次。
将驱动程序类对象注册到驱动程序管理器的一种方法是DriverManager类的registerDriver()方法。对于此方法,您需要将Driver对象作为参数传递。//Instantiating a driver class Driver driver = new com.mysql.jdbc.Driver();
//Registering the Driver DriverManager.registerDriver(driver);
所有驱动程序列表
您可以使用该类的getDrivers()方法获取在该DriverManager类中注册的所有驱动程序的列表。此方法返回一个包含驱动程序列表的枚举。//Retrieving the list of all the Drivers
Enumeration e = DriverManager.getDrivers();
//Printing the list
while(e.hasMoreElements()) {
System.out.println(e.nextElement().getClass());
}
以下JDBC程序使用registerDriver()方法注册了一堆JDBC驱动程序,并使用getDrivers()方法显示它们的列表。
示例import java.sql.Driver;
import java.sql.DriverManager;
import java.util.Enumeration;
public class DriversList_DriverManager {
public static void main(String args[])throws Exception {
//Registering MySQL driver
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//Registering SQLite driver
DriverManager.registerDriver(new org.sqlite.JDBC());
//Registering Oracle driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//Registering Derby-client driver
DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
//Registering Derby-autoloaded driver
DriverManager.registerDriver(new org.apache.derby.jdbc.AutoloadedDriver());
//Registering HSQLDb-JDBC driver
DriverManager.registerDriver(new org.hsqldb.jdbc.JDBCDriver());
System.out.println("List of all the Drivers registered with the DriverManager:");
//Retrieving the list of all the Drivers
Enumeration e = DriverManager.getDrivers();
//Printing the list
while(e.hasMoreElements()) {
System.out.println(e.nextElement().getClass());
}
System.out.println();
}
}
输出结果List of all the Drivers registered with the DriverManager:
class org.sqlite.JDBC
class org.apache.derby.jdbc.ClientDriver
class org.apache.derby.jdbc.AutoloadedDriver
class org.hsqldb.jdbc.JDBCDriver
class com.mysql.jdbc.Driver
class oracle.jdbc.driver.OracleDriver