zoukankan      html  css  js  c++  java
  • 连接池

    1、c3p0连接池

    jar包:

      使用c3p0连接池:

    package cn.getword.utils;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    import java.beans.PropertyVetoException;
    import java.sql.Connection;
    import java.sql.SQLException;
    
    /**
     * 获取连接,Connection是代理对象,close被重写了,不是真正的关闭连接,而是放回连接池中
     *
     */
    public class MySqlPool {
        private static final String DRIVER="";
        private static final String URL="";
        private static final String USRNAME="";
        private static final String PASSWORD="";
        private static ComboPooledDataSource dataSource;
        static {
            dataSource =new ComboPooledDataSource();
            try {
                dataSource.setDriverClass("");
                dataSource.setJdbcUrl("");
                dataSource.setUser("");
                dataSource.setPassword("");
    
                //配置连接池相关的参数
                dataSource.setMaxPoolSize(5);
                dataSource.setMinPoolSize(2);
            } catch (PropertyVetoException e) {
                e.printStackTrace();
            }
        }
        private MySqlPool(){}
        private static final MySqlPool INSTANCE = new MySqlPool();
        public static MySqlPool getInstance(){
            return INSTANCE;
        }
    
        //连接只能一个一个取
        public synchronized Connection getConnection() throws SQLException {
            Connection connection = null;
            connection = dataSource.getConnection();
            return connection;
        }
    
    }
    View Code

      这里的close并不是真的关闭连接,而是放回连接池中。因此,使用完后必须 close。

      如果连接池中的连接全部被取出,那么有人再次取出时,就会等待

    2.Spring的JdbcTemplate

    org.springframework.jdbc.core.JdbcTemplate;

        public List<User> findAll() {
            return jdbcTemplate.query("select * from t_user", ParameterizedBeanPropertyRowMapper.newInstance(User.class));
        }

    end

  • 相关阅读:
    数据库索引的作用和优势缺点
    Python 新浪微博元素 (Word, Screen Name)词汇多样性
    解决Myeclipse在port占用,导致tomcat无法启动。(Linux)
    linux命名管道通信过程
    Lua环境搭建之使用EditPlus搭建Lua开发环境
    详解LUA开发工具及其环境配置
    UltraEdit配置python和lua环境
    Lua学习笔记
    Linux 安装ibus极点五笔输入法备忘录
    win2k/xp查看当前进程
  • 原文地址:https://www.cnblogs.com/zhuxiang1633/p/9641425.html
Copyright © 2011-2022 走看看