FileDocCategorySizeDatePackage
DriverManager.javaAPI DocJava SE 5 API19465Fri Aug 26 14:57:18 BST 2005java.sql

DriverManager

public class DriverManager extends Object

The basic service for managing a set of JDBC drivers.
NOTE: The {@link DataSource} interface, new in the JDBC 2.0 API, provides another way to connect to a data source. The use of a DataSource object is the preferred means of connecting to a data source.

As part of its initialization, the DriverManager class will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to customize the JDBC Drivers used by their applications. For example in your ~/.hotjava/properties file you might specify:

jdbc.drivers=foo.bah.Driver:wombat.sql.Driver:bad.taste.ourDriver
A program can also explicitly load JDBC drivers at any time. For example, the my.sql.Driver is loaded with the following statement:
Class.forName("my.sql.Driver");

When the method getConnection is called, the DriverManager will attempt to locate a suitable driver from amongst those loaded at initialization and those loaded explicitly using the same classloader as the current applet or application.

Starting with the Java 2 SDK, Standard Edition, version 1.3, a logging stream can be set only if the proper permission has been granted. Normally this will be done with the tool PolicyTool, which can be used to grant permission java.sql.SQLPermission "setLog".

see
Driver
see
Connection

Fields Summary
static final SQLPermission
SET_LOG_PERMISSION
The SQLPermission constant that allows the setting of the logging stream.
private static Vector
drivers
private static int
loginTimeout
private static PrintWriter
logWriter
private static PrintStream
logStream
private static boolean
initialized
private static Object
logSync
Constructors Summary
private DriverManager()

Methods Summary
public static synchronized voidderegisterDriver(java.sql.Driver driver)
Drops a driver from the DriverManager's list. Applets can only deregister drivers from their own classloaders.

param
driver the JDBC Driver to drop
exception
SQLException if a database access error occurs

	// Gets the classloader of the code that called this method, may 
	// be null.
	ClassLoader callerCL = DriverManager.getCallerClassLoader();
	println("DriverManager.deregisterDriver: " + driver);
      
	// Walk through the loaded drivers.
	int i;
	DriverInfo di = null;
	for (i = 0; i < drivers.size(); i++) {
	    di = (DriverInfo)drivers.elementAt(i);
	    if (di.driver == driver) {
		break;
	    }
	}
	// If we can't find the driver just return.
	if (i >= drivers.size()) {
	    println("    couldn't find driver to unload");
	    return;
	}
      
	// If the caller does not have permission to load the driver then 
	// throw a security exception.
	if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
	    throw new SecurityException();
	}
      
	// Remove the driver.  Other entries in drivers get shuffled down.
	drivers.removeElementAt(i);
      
    
private static java.lang.ClassgetCallerClass(java.lang.ClassLoader callerClassLoader, java.lang.String driverClassName)

	Class callerC = null;

	try {
	    callerC = Class.forName(driverClassName, true, callerClassLoader);
	}
	catch (Exception ex) {
	    callerC = null;           // being very careful 
	}

	return callerC;
    
private static native java.lang.ClassLoadergetCallerClassLoader()

private static synchronized java.sql.ConnectiongetConnection(java.lang.String url, java.util.Properties info, java.lang.ClassLoader callerCL)

	
        /*
	 * When callerCl is null, we should check the application's
	 * (which is invoking this class indirectly)
	 * classloader, so that the JDBC driver class outside rt.jar
	 * can be loaded from here.
	 */
	if(callerCL == null) {
	    callerCL = Thread.currentThread().getContextClassLoader();
	}    
	  
	if(url == null) {
	    throw new SQLException("The url cannot be null", "08001");
	}
    
	println("DriverManager.getConnection(\"" + url + "\")");
    
	if (!initialized) {
	    initialize();
	}

	// Walk through the loaded drivers attempting to make a connection.
	// Remember the first exception that gets raised so we can reraise it.
	SQLException reason = null;
	for (int i = 0; i < drivers.size(); i++) {
	    DriverInfo di = (DriverInfo)drivers.elementAt(i);
      
	    // If the caller does not have permission to load the driver then 
	    // skip it.
	    if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
		println("    skipping: " + di);
		continue;
	    }
	    try {
		println("    trying " + di);
		Connection result = di.driver.connect(url, info);
		if (result != null) {
		    // Success!
		    println("getConnection returning " + di);
		    return (result);
		}
	    } catch (SQLException ex) {
		if (reason == null) {
		    reason = ex;
		}
	    }
	}
    
	// if we got here nobody could connect.
	if (reason != null)    {
	    println("getConnection failed: " + reason);
	    throw reason;
	}
    
	println("getConnection: no suitable driver");
	throw new SQLException("No suitable driver", "08001");
    
public static synchronized java.sql.ConnectiongetConnection(java.lang.String url, java.util.Properties info)
Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

param
url a database url of the form jdbc:subprotocol:subname
param
info a list of arbitrary string tag/value pairs as connection arguments; normally at least a "user" and "password" property should be included
return
a Connection to the URL
exception
SQLException if a database access error occurs

  
        // Gets the classloader of the code that called this method, may 
	// be null.
	ClassLoader callerCL = DriverManager.getCallerClassLoader();

        return (getConnection(url, info, callerCL));
    
public static synchronized java.sql.ConnectiongetConnection(java.lang.String url, java.lang.String user, java.lang.String password)
Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

param
url a database url of the form jdbc:subprotocol:subname
param
user the database user on whose behalf the connection is being made
param
password the user's password
return
a connection to the URL
exception
SQLException if a database access error occurs

        java.util.Properties info = new java.util.Properties();

        // Gets the classloader of the code that called this method, may 
	// be null.
	ClassLoader callerCL = DriverManager.getCallerClassLoader();

	if (user != null) {
	    info.put("user", user);
	}
	if (password != null) {
	    info.put("password", password);
	}

        return (getConnection(url, info, callerCL));
    
public static synchronized java.sql.ConnectiongetConnection(java.lang.String url)
Attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

param
url a database url of the form jdbc:subprotocol:subname
return
a connection to the URL
exception
SQLException if a database access error occurs


        java.util.Properties info = new java.util.Properties();

        // Gets the classloader of the code that called this method, may 
	// be null.
	ClassLoader callerCL = DriverManager.getCallerClassLoader();

        return (getConnection(url, info, callerCL));
    
public static synchronized java.sql.DrivergetDriver(java.lang.String url)
Attempts to locate a driver that understands the given URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

param
url a database URL of the form jdbc:subprotocol:subname
return
a Driver object representing a driver that can connect to the given URL
exception
SQLException if a database access error occurs

        println("DriverManager.getDriver(\"" + url + "\")");

        if (!initialized) {
            initialize();
        }

        // Gets the classloader of the code that called this method, may 
	// be null.
	ClassLoader callerCL = DriverManager.getCallerClassLoader();

        // Walk through the loaded drivers attempting to locate someone
	// who understands the given URL.
        for (int i = 0; i < drivers.size(); i++) {
            DriverInfo di = (DriverInfo)drivers.elementAt(i);
	    // If the caller does not have permission to load the driver then 
	    // skip it.
            if ( getCallerClass(callerCL, di.driverClassName ) != 
		 di.driverClass ) {
                println("    skipping: " + di);
                continue;
            }
            try {
                println("    trying " + di);
		if (di.driver.acceptsURL(url)) {
		    // Success!
                    println("getDriver returning " + di);
                    return (di.driver);
                }
            } catch (SQLException ex) {
		// Drop through and try the next driver.
            }
        }

        println("getDriver: no suitable driver");
        throw new SQLException("No suitable driver", "08001");
    
public static synchronized java.util.EnumerationgetDrivers()
Retrieves an Enumeration with all of the currently loaded JDBC drivers to which the current caller has access.

Note: The classname of a driver can be found using d.getClass().getName()

return
the list of JDBC Drivers loaded by the caller's class loader

        java.util.Vector result = new java.util.Vector();

        if (!initialized) {
            initialize();
        }

        // Gets the classloader of the code that called this method, may 
	// be null.
	ClassLoader callerCL = DriverManager.getCallerClassLoader();

        // Walk through the loaded drivers.
        for (int i = 0; i < drivers.size(); i++) {
            DriverInfo di = (DriverInfo)drivers.elementAt(i);
	    // If the caller does not have permission to load the driver then 
	    // skip it.
            if ( getCallerClass(callerCL, di.driverClassName ) != di.driverClass ) {
                println("    skipping: " + di);
                continue;
            }
            result.addElement(di.driver);
        }

        return (result.elements());
    
public static java.io.PrintStreamgetLogStream()
Retrieves the logging/tracing PrintStream that is used by the DriverManager and all drivers.

return
the logging/tracing PrintStream; if disabled, is null
deprecated
see
#setLogStream

        return logStream;
    
public static java.io.PrintWritergetLogWriter()
Retrieves the log writer. The getLogWriter and setLogWriter methods should be used instead of the get/setlogStream methods, which are deprecated.

return
a java.io.PrintWriter object
see
#setLogWriter
since
1.2


    //--------------------------JDBC 2.0-----------------------------

                                         
        
	synchronized (logSync) {
	    return logWriter;
	}
    
public static intgetLoginTimeout()
Gets the maximum time in seconds that a driver can wait when attempting to log in to a database.

return
the driver login time limit in seconds
see
#setLoginTimeout

        return (loginTimeout);
    
static voidinitialize()

        if (initialized) {
            return;
        }
        initialized = true;
        loadInitialDrivers();
        println("JDBC DriverManager initialized");
    
private static voidloadInitialDrivers()

        String drivers;
        try {
	    drivers = (String) java.security.AccessController.doPrivileged(
		new sun.security.action.GetPropertyAction("jdbc.drivers"));
        } catch (Exception ex) {
            drivers = null;
        }
        println("DriverManager.initialize: jdbc.drivers = " + drivers);
        if (drivers == null) {
            return;
        }
        while (drivers.length() != 0) {
            int x = drivers.indexOf(':");
            String driver;
            if (x < 0) {
                driver = drivers;
                drivers = "";
            } else {
                driver = drivers.substring(0, x);
                drivers = drivers.substring(x+1);
            }
            if (driver.length() == 0) {
                continue;
            }
            try {
                println("DriverManager.Initialize: loading " + driver);
                Class.forName(driver, true,
			      ClassLoader.getSystemClassLoader());
            } catch (Exception ex) {
                println("DriverManager.Initialize: load failed: " + ex);
            }
        }
    
public static voidprintln(java.lang.String message)
Prints a message to the current JDBC log stream.

param
message a log or tracing message

	synchronized (logSync) {
	    if (logWriter != null) {
		logWriter.println(message);
		
		// automatic flushing is never enabled, so we must do it ourselves
		logWriter.flush();
	    }
	}
    
public static synchronized voidregisterDriver(java.sql.Driver driver)
Registers the given driver with the DriverManager. A newly-loaded driver class should call the method registerDriver to make itself known to the DriverManager.

param
driver the new JDBC Driver that is to be registered with the DriverManager
exception
SQLException if a database access error occurs

	if (!initialized) {
	    initialize();
	}
      
	DriverInfo di = new DriverInfo();
	di.driver = driver;
	di.driverClass = driver.getClass();
	di.driverClassName = di.driverClass.getName();
	drivers.addElement(di);
	println("registerDriver: " + di);
    
public static synchronized voidsetLogStream(java.io.PrintStream out)
Sets the logging/tracing PrintStream that is used by the DriverManager and all drivers.

In the Java 2 SDK, Standard Edition, version 1.3 release, this method checks to see that there is an SQLPermission object before setting the logging stream. If a SecurityManager exists and its checkPermission method denies setting the log writer, this method throws a java.lang.SecurityException.

param
out the new logging/tracing PrintStream; to disable, set to null
deprecated
throws
SecurityException if a security manager exists and its checkPermission method denies setting the log stream
see
SecurityManager#checkPermission
see
#getLogStream

        
        SecurityManager sec = System.getSecurityManager();
        if (sec != null) {
            sec.checkPermission(SET_LOG_PERMISSION);
        }

        logStream = out;
	if ( out != null )
	    logWriter = new java.io.PrintWriter(out);
	else
	    logWriter = null;
    
public static voidsetLogWriter(java.io.PrintWriter out)
Sets the logging/tracing PrintWriter object that is used by the DriverManager and all drivers.

There is a minor versioning problem created by the introduction of the method setLogWriter. The method setLogWriter cannot create a PrintStream object that will be returned by getLogStream---the Java platform does not provide a backward conversion. As a result, a new application that uses setLogWriter and also uses a JDBC 1.0 driver that uses getLogStream will likely not see debugging information written by that driver.

In the Java 2 SDK, Standard Edition, version 1.3 release, this method checks to see that there is an SQLPermission object before setting the logging stream. If a SecurityManager exists and its checkPermission method denies setting the log writer, this method throws a java.lang.SecurityException.

param
out the new logging/tracing PrintStream object; null to disable logging and tracing
throws
SecurityException if a security manager exists and its checkPermission method denies setting the log writer
see
SecurityManager#checkPermission
see
#getLogWriter
since
1.2


	SecurityManager sec = System.getSecurityManager();
	if (sec != null) {
	    sec.checkPermission(SET_LOG_PERMISSION);
	}
	synchronized (logSync) {
	    logStream = null;
	    logWriter = out;
	}
    
public static voidsetLoginTimeout(int seconds)
Sets the maximum time in seconds that a driver will wait while attempting to connect to a database.

param
seconds the login time limit in seconds
see
#getLoginTimeout

 
        loginTimeout = seconds;