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

  • 相关阅读:
    ZOJ 2158 Truck History
    Knight Moves (zoj 1091 poj2243)BFS
    poj 1270 Following Orders
    poj 2935 Basic Wall Maze (BFS)
    Holedox Moving (zoj 1361 poj 1324)bfs
    ZOJ 1083 Frame Stacking
    zoj 2193 Window Pains
    hdu1412{A} + {B}
    hdu2031进制转换
    openjudge最长单词
  • 原文地址:https://www.cnblogs.com/ShaoXin/p/6840850.html
Copyright © 2011-2022 走看看