Using DriverManager to get a small improvement in database connections, spring gets database connections
When DriverManager is used to obtain database connections, because the DriverManager implementation class has a static code block, you can directly register the driver and manage multiple drivers at the same time.
Therefore, when changing the database connection, you need to specify different databases, so you need to modify the properties configuration file repeatedly (although not troublesome), so I want to write the properties file of each driver Connection Program
When connecting, add a configuration file, which specifies the properties file to be passed in.
First, let's take a look at the file path (why is it difficult to copy and paste images !!!!)
Src
Com. jdbc. java
TestJDBC. java
Properties
JdbcName. properties
MySql. properties
This is basically the case. The first layer is the package. Below are various files.
The Code is as follows:
/*** Specifies the configuration file to be used in a configuration file (good detour ...) ** @ Return * @ throws Exception */public Connection getConnection3 () throws Exception {// four strings to connect to the database // The driver's full class name String driverClass = null; string jdbcUrl = null; String user = null; String password = null; String jdbcName = null; // read jdbcName. properties file InputStream inStream = getClass (). getClassLoader (). getResourceAsStream ("properties/jdbcName. properties "); Properties propertiesOfName = new Properties (); propertiesOfName. load (inStream); jdbcName = propertiesOfName. getProperty ("jdbcName"); // read the required properties file InputStream in = getClass (). getClassLoader (). getResourceAsStream ("properties/" + jdbcName + ". properties "); Properties properties = new Properties (); properties. load (in); driverClass = properties. getProperty ("driver"); jdbcUrl = properties. getProperty ("jdbcUrl"); user = properties. getProperty ("user"); password = properties. getProperty ("password"); // load the database Driver (register the driver) Class. forName (driverClass); Connection connection = DriverManager. getConnection (jdbcUrl, user, password); return connection ;}
The test code is as follows:
@Test public void testGetConnection3() throws Exception { System.out.println(getConnection3()); }
The result is as follows:
com.mysql.jdbc.JDBC4Connection@104a311
Note: When specifying the properties file in this mode, the relative path cannot be selected, and an error is returned.
The code in jdbcName. properties is as follows:
jdbcName=mySql
The code here is not very concise. You only need to write a variety of configuration files such as mySql and Oracle, and then you can change the name in this configuration file to the desired one, minor changes (dedicated for lazy Users ~)