Druid数据源配置
一:添加依赖
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>${druid.version}</version> </dependency>
二:加载配置文件代码
/*** * * @author zhanchaohan * */ public class DruidUtill { public DruidDataSource init() throws FileNotFoundException, IOException { Properties properties=new Properties(); properties.load(DruidUtill.class.getResourceAsStream("/druid.properties")); DruidDataSource dataSource = new DruidDataSource(); dataSource.configFromPropety(properties); return dataSource; } }
三:配置文件
druid.name=myDruid druid.url=jdbc:mysql://localhost:3306/test druid.username=root druid.password= druid.testWhileIdle= druid.testOnBorrow= druid.validationQuery= druid.useGlobalDataSourceStat= druid.useGloalDataSourceStat= druid.asyncInit= druid.filters= druid.timeBetweenLogStatsMillis= druid.stat.sql.MaxSize= druid.clearFiltersEnable= druid.resetStatEnable= druid.notFullTimeoutRetryCount= druid.timeBetweenEvictionRunsMillis= druid.maxWaitThreadCount= druid.maxWait= druid.failFast= druid.phyTimeoutMillis= druid.phyMaxUseCount= druid.minEvictableIdleTimeMillis= druid.maxEvictableIdleTimeMillis= druid.keepAlive= druid.keepAliveBetweenTimeMillis= druid.poolPreparedStatements= druid.initVariants= druid.initGlobalVariants= druid.useUnfairLock= druid.driverClassName= druid.initialSize= druid.minIdle= druid.maxActive= druid.killWhenSocketReadTimeout= druid.connectProperties= druid.maxPoolPreparedStatementPerConnectionSize= druid.initConnectionSqls= druid.load.spifilter.skip= druid.checkExecuteTime=
四:测试
/*** * * @author zhanchaohan * */ public class DruidUtillTest { private DruidDataSource druidDataSource; @Before public void init() throws FileNotFoundException, IOException { DruidUtill du=new DruidUtill(); druidDataSource=du.init(); } @Test public void test1() throws SQLException { DruidPooledConnection dpc= druidDataSource.getConnection(); PreparedStatement preparedStatement=dpc.prepareStatement("show tables"); ResultSet resultSet=preparedStatement.executeQuery(); while(resultSet.next()) { System.out.println(resultSet.getString(1)); } } }