
什么是Druid连接池
阿里巴巴提供的数据连接池,被广泛使用。
如何使用
- Maven导入Druid连接池API和MYSQL数据库驱动API将连接池作为JAVABean在config.java中配置测试是否可用。
实例
pom.xml
mysql mysql-connector-java8.0.15 com.alibaba druid1.1.21
Config.java
@Configuration
@ComponentScan(basePackages = "cn.tedu.demo")
//读取properties
@PropertySource("classpath:jdbc.properties")
public class Config {
//自动获取组件
@Autowired
Environment env;
@Bean
public DataSource dataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(env.getProperty("db.driver"));
ds.setUrl(env.getProperty("db.url"));
ds.setUsername(env.getProperty("db.username"));
ds.setPassword(env.getProperty("db.password"));
ds.setMaxActive(env.getProperty("db.maxActive",Integer.class));
ds.setInitialSize(env.getProperty("db.initialSize",Integer.class));
return ds;
}
}
env.getProperty中的值和properties中的一样
jdbc.properties文件
db.driver=com.mysql.cj.jdbc.Driver db.url=jdbc:mysql://localhost:3306/mysql?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true db.username=root db.password= db.maxActive=10 db.initialSize=2
最后一步测试链接
@Test
public void testDateSource(){
String sql = "select 'Hello World'";
DataSource ds = ctx.getBean("dataSource", DataSource.class);
try(Connection conn = ds.getConnection()){
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);
while (rs.next()){
System.out.println(rs.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)