Spring配置数据源

常见的数据源连接池:DBCP、C3P0、BoneCP、Druid等

1、C3P0

①导入数据源的坐标和数据库驱动坐标


   c3p0
   c3p0
   0.9.1.2


  mysql
  mysql-connector-java
  5.1.47

②创建连接池

  @Test
  public void test1() throws Exception {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://172.16.90.174:3306/dbName");
        dataSource.setUser("root");
        dataSource.setPassword("123456");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

1、Druid

①导入数据源的坐标和数据库驱动坐标


  com.alibaba
  druid
  1.1.23


  mysql
  mysql-connector-java
  5.1.47

②创建连接池

  @Test
    public void test2() throws Exception {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://172.16.90.174:3306/dbName");
        dataSource.setUsername("root");
        dataSource.setPassword("123456");
        Connection connection = dataSource.getConnection();
        System.out.println(connection);
    }

配置文件提取(jdbc.properties)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://172.16.90.174:3306/dbName
jdbc.username=root
jdbc.password=123456

①代码方式

@Test
public void test3() throws Exception {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("jdbc");
        String driver = resourceBundle.getString("jdbc.driver");
        String url = resourceBundle.getString("jdbc.url");
        String username = resourceBundle.getString("jdbc.username");
        String password = resourceBundle.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);
    }

②配置文件方式(applicationContext.xml)



     
    

    
         
        
          
        
         
        
          
        
    

③测试

@Test
public void test4() throws Exception {
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    ComboPooledDataSource dataSource = (ComboPooledDataSource) context.getBean("dataSource");
    Connection connection = dataSource.getConnection();
    System.out.println(connection);
 }

你可能感兴趣的:(Spring配置数据源)