首先是数据库的配置文件,现在把mysql的配置文件放在.properties文件中
这是配置文件的信息名称是:druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.1.60:3306/edudb_app?characterEncoding=utf8
username=root
password=123456
filters=stat
initialSize=10
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
接下来就是获取数据库的连接了
public class DruidPoolConnection {
private static DruidPoolConnection databasePool = null;
private static DruidDataSource dds = null;
static {
Properties properties = loadPropertyFile("druid.properties");
try {
dds = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
private DruidPoolConnection() {}
public static synchronized DruidPoolConnection getInstance() {
if (null == databasePool) {
databasePool = new DruidPoolConnection();
}
return databasePool;
}
public DruidPooledConnection getConnection() throws SQLException {
return dds.getConnection();
}
public static Properties loadPropertyFile(String fullFile) {
String filePath = DruidPoolConnection.class.getClassLoader().getResource(fullFile).getPath();
if (null == fullFile || fullFile.equals(""))
throw new IllegalArgumentException(
"Properties file path can not be null : " + fullFile);
// webRootPath = DruidPoolConnection.class.getClassLoader().getResource(fullFile)
// .getPath();
// webRootPath = new File(webRootPath).getParent();
InputStream inputStream = null;
Properties p = null;
try {
inputStream = new FileInputStream(filePath);
p = new Properties();
p.load(inputStream);
} catch (FileNotFoundException e) {
throw new IllegalArgumentException("Properties file not found: "
+ filePath);
} catch (IOException e) {
throw new IllegalArgumentException(
"Properties file can not be loading: " + filePath);
} finally {
try {
if (inputStream != null)
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return p;
}
}
标红的部分室外街可以调用的方法:
外界获得connection的方法是
DruidPoolConnection .
getInstance ( ) .
getConnection( )