JDBC-Util
JDBC连接池工具类的封装 V1.0
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| package com.xiaobai.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties;
public class JDBCUtil { private static DataSource dataSource;
static { try { Properties properties = new Properties(); InputStream resourceAsStream = JDBCUtil.class.getClassLoader().getResourceAsStream("db.properties"); properties.load(resourceAsStream); dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { throw new RuntimeException(e); } }
public static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(e); } }
public static void close(Connection conn) { try { conn.close(); } catch (SQLException e) { throw new RuntimeException(e); } } }
|
TreadLocal
java.lang.TreadLocal,为解决多线程程序的并发问题的工具类
通常用来在多线程中管理、共享数据库连接、Session等
在Java中,每一个线程对象都有TreadLocalMap<Threadlocal, Object> ,其key是ThreadLocal,Object为该线程的共享对象
JDBC连接池工具类的封装 V2.0
使用Treadlocal改写工具类的意义就是:
同一个线程在多次操作数据库的过程中,用到的是同一个连接
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
| import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties;
public class JDBCUtilV2 { private static DataSource dataSource; private static ThreadLocal<Connection> threadLocal = new ThreadLocal<>(); ;
static { try { Properties properties = new Properties(); InputStream resourceAsStream = JDBCUtilV2.class.getClassLoader().getResourceAsStream("jdbc.properties"); properties.load(resourceAsStream); dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (Exception e) { throw new RuntimeException(e); } }
public static Connection getConnection() { try { Connection connection = threadLocal.get(); if (connection == null) { connection = dataSource.getConnection(); threadLocal.set(connection); } return connection; } catch (SQLException e) { throw new RuntimeException(e); } }
public static void close() { try { Connection connection = threadLocal.get(); if (connection != null) { connection.close(); threadLocal.remove(); } } catch (SQLException e) { throw new RuntimeException(e); } } }
|