DriverManager is a managed class of drives
* 1). The database connection can be obtained through the overloaded getconnection () method, which is more convenient
* 2). Multiple drivers can be managed at the same time, if multiple database connections are registered, when the getconnection () method is called
* Different parameters are passed in, that is, different database connections are returned.
1 PublicConnection GetConnection2 ()throwsException {2 //four strings ready to connect to a database3 //full class name of the drive4String Driverclass =NULL;5String Jdbcurl =NULL;6String user =NULL;7String Password =NULL;8 9 //read the Jdbc.properties file under the ClasspathTenInputStream in = GetClass (). getClassLoader (). getResourceAsStream ("Jdbc.properties"); OneProperties Properties =NewProperties (); A properties.load (in); -Driverclass = Properties.getproperty ("Driver"); -Jdbcurl = Properties.getproperty ("Jdbcurl"); theuser = Properties.getproperty ("User"); -Password = properties.getproperty ("Password"); - - //Load Database driver (register driver) + //Drivermanager.registerdriver ((Driver) - //Class.forName (Driverclass). newinstance ()); + //In fact, a step can be omitted, because the DriverManager implementation class has a static block of code, you can directly register the driver A Class.forName (driverclass); at -Connection Connection =drivermanager.getconnection (jdbcurl, user, password); - returnconnection; -}
Test program
1 @Test 2 Public void throws exception{3 System.out.println (GetConnection2 ()); 4 }
The console output results are as follows
[Email protected]
Get a database connection using DriverManager