MySQL数据源多连接

1.pom下载jar包

        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-dbcp2</artifactId>
			<version>2.6.0</version>
		</dependency>

2.创建db_first.properties。配置数据库连接信息。注意:如果需要多个数据源,则从这个步骤开始重复以下的步骤操作。

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://192.168.X.XX:3306/tableName?autoReconnect=true&useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false
username=root
password=123456

3.数据库连接池

package org.atm.vl.portal.front.utils;
import java.io.InputStream;
import java.sql.*;
import java.util.*;
import javax.sql.DataSource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.springframework.stereotype.Component;

@Component
public class DBCPFirstUtils {
    // 加载名称为mysqlConn 的配置(src下放置 db_dbcp.properties 配置文件)
    private static BasicDataSource ds = null;

    /**
     * 定义一个ThreadLocal,绑定Connection,每个线程对应一个Connection,执行事务使用
     */
    private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

    static {
        Properties props = new Properties();
        try {
            // 1.加载Properties文件输入流。配置你自己的db_first.properties的文件位置
            InputStream is = DBCPFirstUtils.class.getClassLoader().getResourceAsStream("com/kd/config/internal/db_first.properties");
            // 2.加载载配置
            props.load(is);
            is.close();
            // 3. 创建数据源
            ds = BasicDataSourceFactory.createDataSource(props);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @return BasicDataSource
     */
    public static DataSource getDataSource() {
        return ds;
    }

    /**
     *
     * @return 由BasicDataSource创建的 Connection
     */
    public static Connection getConnection() {
        try {
            return ds.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *
     * @return 获取当前线程绑定的Connection
     * @throws SQLException
     */
    public static Connection getTranConnection() throws SQLException{
        //得到ThreadLocal中的connection
        Connection conn = tl.get();
        //判断conn是否为空,如果不为空,则说明事务已经开启
        if(conn == null){
            conn = getConnection();
            //把当前开启的事务放入ThreadLocal中
            tl.set(conn);
        }
        return conn;
    }


    /**
     * 开启事务,如果当前线程中没有Connection,则创建该线程对应的一个Connection
     * @throws SQLException
     */
    public static void beginTran() throws SQLException {
        //设置事务提交为手动
        getTranConnection().setAutoCommit(false);
    }


    /**
     * 提交事务
     * @throws SQLException
     */
    public static void commit() throws SQLException {
        //得到ThreadLocal中的connection
        Connection conn = getTranConnection();
        //判断conn是否为空,如果为空,则说明没有开启事务
        if(conn != null){
            //如果conn不为空,提交事务
            conn.commit();
            //事务提交后,关闭连接
            conn.close();
            //将连接移出ThreadLocal
            tl.remove();
        }
    }

    /**
     * 回滚事务
     * @throws SQLException
     */
    public static void rollback() throws SQLException {
        //得到ThreadLocal中的connection
        Connection conn = getTranConnection();
        //判断conn是否为空,如果为空,则说明没有开启事务,也就不能回滚事务
        if(conn != null){
            //事务回滚
            conn.rollback();
            //事务回滚后,关闭连接
            conn.close();
            //将连接移出ThreadLocal
            tl.remove();
        }
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {
        Connection connection = DBCPFirstUtils.getConnection();
        try {
            PreparedStatement preparedStatement = connection.prepareStatement("select * from tableName limit 20");
            ResultSet resultSet = preparedStatement.executeQuery();

            List<Map<String, Object>> list = new ArrayList<>();

            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();// ResultSet列数

            while (resultSet.next()) {

                //我需要结果集转为格式为:List<Map<String,Object>>。
                Map<String, Object> map = new HashMap<>();
                for (int i = 1; i <= columnCount; i++) {// 遍历获取对当前行的每一列的键值对,put到map中
                    // rs.getObject(i) 获得当前行某一列字段的值
                    map.put(metaData.getColumnName(i).toLowerCase(), resultSet.getObject(i));
                }
                list.add(map);

                //不需要转,直接打印方式有两种。
                //第一种:resultSet.getString(1):参数为第几列
                System.out.println(resultSet.getString(1) + "--" + resultSet.getString(2));
                //第二种:resultSet.getString("columnName"):参数字段名称

            }

            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 

 

 

 

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值