利用DriverManagerDataSource测试数据库是否正常连接,每次只返回一个connection
package com.db;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import java.io.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
/**
* @author Duoduo
* @version 1.0
* @date 2017/4/23 17:15
*/
public class DataBaseConnect {
public boolean getConnection() {
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
Properties dbProperties = new Properties();
try {
dbProperties.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(dbProperties.getProperty("jdbc.driver"));
dataSource.setUrl(dbProperties.getProperty("jdbc.url"));
dataSource.setUsername(dbProperties.getProperty("jdbc.username"));
dataSource.setPassword(dbProperties.getProperty("jdbc.password"));
Connection connection = null;
try {
connection = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
System.out.println(connection);
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
return true;
}
}