zoukankan      html  css  js  c++  java
  • 使用DBCP便利链接数据库以及使用链接池

    package com.dbcp.cn;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.util.Properties;
    
    import javax.sql.DataSource;
    
    import org.apache.commons.dbcp.BasicDataSource;
    import org.apache.commons.dbcp.BasicDataSourceFactory;
    import org.junit.Test;
    
    public class DBCP_Test {
        /**
         * 硬链接
         * 
         * @throws Exception
         */
        @Test
        public void dbcp_test_old() throws Exception {
            BasicDataSource dataSource = new BasicDataSource();
            dataSource.setUrl("jdbc:mysql://localhost:3306/staff");
            dataSource.setUsername("root");
            dataSource.setPassword("123456");
            dataSource.setInitialSize(3);// 设置链接池初始值
            dataSource.setMaxActive(6);// 设置最大连接数
            dataSource.setMaxIdle(3000);// 设置最大活跃时间
            dataSource.setDriverClassName("com.mysql.jdbc.Driver");
            Connection connection = dataSource.getConnection();
            PreparedStatement prepareStatement = connection.prepareStatement("delete from user where id=16");
            prepareStatement.executeUpdate();
            prepareStatement.close();
            connection.close();
        }
    
        /**
         * 配置方式实现链接
         * @throws Exception
         */
        @Test
        public void dbcp_test() throws Exception {
            Properties properties = new Properties();//配置文件
            properties.load(DBCP_Test.class.getResourceAsStream("/db.properties"));
            DataSource dataSource = BasicDataSourceFactory.createDataSource(properties);
            Connection connection = dataSource.getConnection();
            PreparedStatement prepareStatement = connection.prepareStatement("delete from user where id=17");
            prepareStatement.executeUpdate();
            prepareStatement.close();
            connection.close();
        }
    }
    url=jdbc:mysql://localhost:3306/staff
    username=root
    password=123456
    driverClassName=com.mysql.jdbc.Driver

    需要导入三个jar包

    commons-dbcp-1.4.jar

    commons-pool-1.5.6.jar

    mysql-connector-java-5.1.7-bin.jar

  • 相关阅读:
    SolrCloud阶段总结
    Solr总结
    机器学习算法与Python实践之(六)二分k均值聚类
    机器学习问题方法总结
    浅谈Kmeans聚类
    AVL树的算法思路整理
    Solr4.6从数据库导数据的步骤
    红黑树
    浅谈 Adaboost 算法
    POJ 1836 Alignment
  • 原文地址:https://www.cnblogs.com/ShaoXin/p/6840850.html
Copyright © 2011-2022 走看看