Because there is a static block of code in the DriverManager implementation class when using DriverManager to get a database connection, you can register the driver directly and you can manage multiple drivers at the same time
So if you need to specify a different database when swapping the database connection, you need to modify the properties configuration file (although it's not a hassle), so I want to write the properties file for each driver connection program.
When connecting, add a configuration file that specifies which properties file to pass in the configuration file
First look at the file path (picture copy and paste why not good!!!!) )
Src
Com.jdbc.java
Testjdbc.java
Properties
Jdbcname.properties
Mysql.properties
Anyway, basically, the first layer is the package, and here are the various files
The code is as follows
/*** Specify a configuration file to choose which profile to use (Good wrap ... ) * *@return * @throwsException*/ PublicConnection GetConnection3 ()throwsException {//four strings ready to connect to a database//full class name of the driveString Driverclass =NULL; String Jdbcurl=NULL; String User=NULL; String Password=NULL; String Jdbcname=NULL; //Read Jdbcname.properties fileInputStream instream = GetClass (). getClassLoader (). getResourceAsStream ("Properties/jdbcname.properties"); Properties Propertiesofname=NewProperties (); Propertiesofname.load (instream); Jdbcname= Propertiesofname.getproperty ("Jdbcname"); //read the desired properties fileInputStream in =getclass (). getClassLoader (). getResourceAsStream ("properties/" + Jdbcname + ". Properties"); Properties Properties=NewProperties (); Properties.load (in); Driverclass= Properties.getproperty ("Driver"); Jdbcurl= Properties.getproperty ("Jdbcurl"); User= Properties.getproperty ("User"); Password= Properties.getproperty ("Password"); //Load Database driver (register driver)Class.forName (Driverclass); Connection Connection=drivermanager.getconnection (jdbcurl, user, password); returnconnection; }
The test code is as follows
@Test Public void throws Exception { System.out.println (GetConnection3 ()); }
The results are as follows
[Email protected]
Issues to be aware of: This method specifies the properties file when the relative path is not selected and an error occurs
The code in Jdbcname.properties is as follows
Jdbcname=mysql
The code here is not very concise, just a variety of what mysql,oracle and other configuration files to write, and then want to use which of the configuration file to change the name of the line, the change is very small (lazy people dedicated ~)
A small improvement to get a database connection using DriverManager