栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring配置数据源(数据库)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring配置数据源(数据库)

数据库(连接池)的作用

数据源是提高程序性能出现的事先实例化数据源,初始化部分连接资源使用连接资源时从数据源中获取使用完毕后将连接资源归还给数据源

常见的数据源:DBCP、C3p0、BoneCP、Druid等

数据源的开发步骤
    导入数据源的坐标和数据库驱动坐标
    数据源坐标

      com.alibaba
      druid
      1.1.10
    

或者


      c3p0
      c3p0
      0.9.1.2
    

数据库驱动坐标


      mysql
      mysql-connector-java
      5.1.49
    

junit坐标


      junit
      junit
      4.11
      test

    创建数据源对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();

    设置数据源的基本连接数据
 dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
    使用数据源获取链接资源和归还连接资源
 Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
抽取配置文件


jdbc。properties中的内容

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/sell?useSSL=false
jdbc.username=root
jdbc.password=111111
public void test3() throws Exception {
        //读取配置文件
        ResourceBundle rb = ResourceBundle.getBundle("jdbc");
        String driver = rb.getString("jdbc.driver");
        String url = rb.getString("jdbc.url");
        String username = rb.getString("jdbc.username");
        String password = rb.getString("jdbc.password");
        //创建数据源对象
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass(driver);
        dataSource.setJdbcUrl(url);
        dataSource.setUser(username);
        dataSource.setPassword(password);
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
        connection.close();
    }
Spring配置数据源

导入spring-context坐标


      org.springframework
      spring-context
      5.2.5.RELEASE

配置xml文件,需要引入context命名空间和约束路径



 
    


        
        
        
        
        

测试

 public void test4() throws Exception {
        ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml");
        DataSource data = app.getBean(DataSource.class);
        Connection connection = data.getConnection();
        System.out.println(connection);
        connection.close();

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/763329.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号