1703-MySQL-DBCP连接池配置


1.DBCP

DBCP(DataBase connection pool),数据库连接池。是 apache 上的一个 Java 连接池项目,也是 tomcat 使用的连接池组件。单独使用dbcp需要2个包:
commons-dbcp.jar
commons-pool.jar

2.配置DBCP

配置文件:db.properties

driver=com.mysql.jdbc.Driver
url=jdbc\:mysql\://localhost\:3306/test?useUnicode\=true&characterEncoding\=utf8
username=root
password=root

3.工具类DBCP

package com.it.jdbc.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import javax.management.RuntimeErrorException;
import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSourceFactory;

public class DBCPUtils {
    private static DataSource dataSource;
    static {
        try {
            //加载找properties文件输入流
            InputStream is = DBCPUtils.class.getClassLoader()
                    .getResourceAsStream("db.properties");
            //加载输入流
            Properties props = new Properties();
            props.load(is);
            //创建数据源
            dataSource = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }
    
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
}
}

4.测试DBCP

package com.it.jdbc.TestDataSoure;

import java.sql.Connection;
import java.sql.PreparedStatement;

import org.junit.Test;

import com.it.jdbc.utils.DBCPUtils;

public class TestDBCP {
            @Test
            public void testUpdataId(){
                Connection conn =null;
                PreparedStatement pstmt = null;
                try{
                    conn =DBCPUtils.getConnection();
                    String sql ="update use1 set upassword=? where uid=?;";
                    pstmt= conn.prepareStatement(sql);
                    pstmt.setString(1,"张三");
                    pstmt.setInt(2,11);
                    pstmt.setInt(2,10);
                    int rows=pstmt.executeUpdate();
                    if(rows>0){
                        System.out.println("更新成功");
                    }else {
                        System.out.println("更新失败");
                    }
                }catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
}

你可能感兴趣的:(1703-MySQL-DBCP连接池配置)