Druid连接池工具类,连接多个不同数据库需求
一、获取不同数据库连接
1.需要连接一系列的数据库
2.数据库会动态改变,比如新增和删除数据库
代码如下:
1 package com.chinaoly.utils; 2 3 import com.alibaba.druid.pool.DruidDataSource; 4 import com.alibaba.druid.pool.DruidDataSourceFactory; 5 import com.chinaoly.database.entity.DataBase; 6 import com.chinaoly.database.service.DataBaseService; 7 import java.sql.PreparedStatement; 8 import java.sql.ResultSet; 9 import java.sql.SQLException; 10 import java.time.LocalDate; 11 import java.time.LocalDateTime; 12 import java.time.ZoneId; 13 import java.util.HashMap; 14 import java.util.List; 15 import java.util.Map; 16 import java.util.Properties; 17 import javax.annotation.Resource; 18 import javax.sql.DataSource; 19 import java.sql.Connection; 20 import org.joda.time.LocalTime; 21 import org.springframework.stereotype.Component; 22 23 24 public class DruidUtil { 25 26 private static DruidUtil single = null; 27 28 public static Map<String,DruidDataSource> map = new HashMap<>(); 29 30 public DruidUtil() { 31 } 32 33 public DruidUtil(List<DataBase> allDBs) { 34 for (DataBase db:allDBs) { 35 Properties prop = new Properties(); 36 if("Mysql".equalsIgnoreCase(db.getType())){ 37 prop.setProperty("driver","com.mysql.jdbc.Driver"); 38 prop.setProperty("url","jdbc:mysql://"+db.getIpAddress()+":"+db.getPort()+"/"+db.getName()); 39 prop.setProperty("connectionProperties","useUnicode=true;characterEncoding=UTF8"); 40 }else if ("Oracle".equalsIgnoreCase(db.getType())){ 41 prop.setProperty("driver","oracle.jdbc.driver.OracleDriver"); 42 prop.setProperty("url","jdbc:oracle:thin:@"+db.getIpAddress()+":"+db.getPort()+":"+db 43 .getName()); 44 }else if("Hive".equalsIgnoreCase(db.getType())){ 45 prop.setProperty("driver","org.apache.hive.jdbc.HiveDriver"); 46 prop.setProperty("url","jdbc:hive2://"+db.getIpAddress()+":"+db.getPort()+"/"+db.getName()); 47 }else { 48 throw new RuntimeException("连接池目前只支持Mysql、Oracle、Hive三种数据库类型!"); 49 } 50 prop.setProperty("username",db.getUserName()); 51 String passwd = EncryptUtil.aesDecrypt(db.getPasswd()); 52 prop.setProperty("password",passwd); 53 prop.setProperty("initialSize","3"); 54 prop.setProperty("maxActive","6"); 55 prop.setProperty("minIdle","1"); 56 prop.setProperty("maxWait","60000"); 57 prop.setProperty("filters","stat"); 58 prop.setProperty("timeBetweenEvictionRunsMillis","35000"); 59 prop.setProperty("minEvictableIdleTimeMillis","30000"); 60 prop.setProperty("testWhileIdle","true"); 61 prop.setProperty("testOnBorrow","false"); 62 prop.setProperty("testOnReturn","false"); 63 prop.setProperty("poolPreparedStatements","false"); 64 prop.setProperty("maxPoolPreparedStatementPerConnectionSize","200"); 65 prop.setProperty("removeAbandoned","true"); 66 try { 67 DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory 68 .createDataSource(prop); 69 map.put(db.getId(),druidDataSource); 70 } catch (Exception e) { 71 e.printStackTrace(); 72 System.out.println("初始化创建连接池失败!"); 73 } 74 } 75 } 76 77 /** 78 * 获取实例 79 * @return 80 */ 81 public static DruidUtil getInstance(){ 82 if (single == null) { 83 synchronized (DruidUtil.class) { 84 if (single == null) { 85 single = new DruidUtil(); 86 } 87 } 88 } 89 return single; 90 } 91 92 public Connection getConnection(String id) throws SQLException { 93 DruidDataSource source = map.get(id); 94 return source.getConnection(); 95 } 96 97 public void addDataBaseIn(DataBase db){ 98 Properties prop = new Properties(); 99 if("Mysql".equalsIgnoreCase(db.getType())){ 100 prop.setProperty("driverClassName","com.mysql.jdbc.Driver"); 101 prop.setProperty("validationQuery","SELECT 1 FROM DUAL"); 102 prop.setProperty("url","jdbc:mysql://"+db.getIpAddress()+":"+db.getPort()+"/"+db.getName()); 103 prop.setProperty("connectionProperties","useUnicode=true;characterEncoding=UTF8"); 104 }else if ("Oracle".equalsIgnoreCase(db.getType())){ 105 prop.setProperty("driverClassName","oracle.jdbc.driver.OracleDriver"); 106 prop.setProperty("validationQuery","SELECT 1 FROM DUAL"); 107 prop.setProperty("url","jdbc:oracle:thin:@"+db.getIpAddress()+":"+db.getPort()+":"+db 108 .getName()); 109 }else if("Hive".equalsIgnoreCase(db.getType())){ 110 prop.setProperty("driverClassName","org.apache.hive.jdbc.HiveDriver"); 111 prop.setProperty("validationQuery","SELECT 1"); 112 prop.setProperty("url","jdbc:hive2://"+db.getIpAddress()+":"+db.getPort()+"/"+db.getName()); 113 }else { 114 throw new RuntimeException("连接池目前只支持Mysql、Oracle、Hive三种数据库类型!"); 115 } 116 prop.setProperty("username",db.getUserName()); 117 String passwd = EncryptUtil.aesDecrypt(db.getPasswd()); 118 prop.setProperty("password",passwd); 119 prop.setProperty("initialSize","3"); 120 prop.setProperty("maxActive","10"); 121 prop.setProperty("minIdle","3"); 122 prop.setProperty("maxWait","60000"); 123 prop.setProperty("filters","stat"); 124 prop.setProperty("timeBetweenEvictionRunsMillis","35000"); 125 prop.setProperty("minEvictableIdleTimeMillis","30000"); 126 prop.setProperty("testWhileIdle","true"); 127 prop.setProperty("testOnBorrow","false"); 128 prop.setProperty("testOnReturn","false"); 129 prop.setProperty("poolPreparedStatements","false"); 130 prop.setProperty("maxPoolPreparedStatementPerConnectionSize","200"); 131 prop.setProperty("removeAbandoned","true"); 132 try { 133 DruidDataSource druidDataSource = (DruidDataSource) DruidDataSourceFactory 134 .createDataSource(prop); 135 map.put(db.getId(),druidDataSource); 136 } catch (Exception e) { 137 e.printStackTrace(); 138 System.out.println("新增数据库创建连接池失败!"); 139 } 140 } 141 142 public void removeDataBaseOut(DataBase db){ 143 DruidDataSource source = map.get(db.getId()); 144 source.close(); 145 map.remove(db.getId()); 146 } 147 148 public boolean containsId(String id){ 149 return map.containsKey(id); 150 } 151 }
二、获取数据库表或表字段类型、注释等信息
1 public class DatabaseUtilTest { 2 private static final Logger logger = LoggerFactory.getLogger(DatabaseUtilTest.class); 3 private static final String DRIVER = "com.mysql.jdbc.Driver"; 4 private static final String DATABASE_URL = "jdbc:mysql://ip:3306/databasename?useUnicode=true&characterEncoding=utf8"; 5 private static final String USERNAME = "xxx"; 6 private static final String PASSWORD = "xxx"; 7 private static final String SQL = "SELECT * FROM ";// 数据库操作 8 static { 9 try { 10 Class.forName(DRIVER); 11 } catch (ClassNotFoundException e) { 12 logger.error("can not load jdbc driver", e); 13 } 14 } 15 /** 16 * 获取数据库连接 17 * 18 * @return 19 */ 20 public static Connection getConnection() { 21 Connection conn = null; 22 try { 23 conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD); 24 } catch (SQLException e) { 25 logger.error("get connection failure", e); 26 } 27 return conn; 28 } 29 /** 30 * 关闭数据库连接 31 * @param conn 32 */ 33 public static void closeConnection(Connection conn) { 34 if(conn != null) { 35 try { 36 conn.close(); 37 } catch (SQLException e) { 38 logger.error("close connection failure", e); 39 } 40 } 41 } 42 /** 43 * 获取数据库下的所有表名 44 */ 45 public static List<String> getTableNames() { 46 List<String> tableNames = new ArrayList<>(); 47 Connection conn = getConnection(); 48 ResultSet rs = null; 49 try { 50 //获取数据库的元数据 51 DatabaseMetaData db = conn.getMetaData(); 52 //从元数据中获取到所有的表名 53 rs = db.getTables(null, null, null, new String[] { "TABLE" }); 54 while(rs.next()) { 55 tableNames.add(rs.getString(3)); 56 } 57 } catch (SQLException e) { 58 logger.error("getTableNames failure", e); 59 } finally { 60 try { 61 rs.close(); 62 closeConnection(conn); 63 } catch (SQLException e) { 64 logger.error("close ResultSet failure", e); 65 } 66 } 67 return tableNames; 68 } 69 /** 70 * 获取表中所有字段名称 71 * @param tableName 表名 72 * @return 73 */ 74 public static List<String> getColumnNames(String tableName) { 75 List<String> columnNames = new ArrayList<>(); 76 //与数据库的连接 77 Connection conn = getConnection(); 78 PreparedStatement pStemt = null; 79 String tableSql = SQL + tableName; 80 try { 81 pStemt = conn.prepareStatement(tableSql); 82 //结果集元数据 83 ResultSetMetaData rsmd = pStemt.getMetaData(); 84 //表列数 85 int size = rsmd.getColumnCount(); 86 for (int i = 0; i < size; i++) { 87 columnNames.add(rsmd.getColumnName(i + 1)); 88 } 89 } catch (SQLException e) { 90 logger.error("getColumnNames failure", e); 91 } finally { 92 if (pStemt != null) { 93 try { 94 pStemt.close(); 95 closeConnection(conn); 96 } catch (SQLException e) { 97 logger.error("getColumnNames close pstem and connection failure", e); 98 } 99 } 100 } 101 return columnNames; 102 } 103 /** 104 * 获取表中所有字段类型 105 * @param tableName 106 * @return 107 */ 108 public static List<String> getColumnTypes(String tableName) { 109 List<String> columnTypes = new ArrayList<>(); 110 //与数据库的连接 111 Connection conn = getConnection(); 112 PreparedStatement pStemt = null; 113 String tableSql = SQL + tableName; 114 try { 115 pStemt = conn.prepareStatement(tableSql); 116 //结果集元数据 117 ResultSetMetaData rsmd = pStemt.getMetaData(); 118 //表列数 119 int size = rsmd.getColumnCount(); 120 for (int i = 0; i < size; i++) { 121 columnTypes.add(rsmd.getColumnTypeName(i + 1)); 122 } 123 } catch (SQLException e) { 124 logger.error("getColumnTypes failure", e); 125 } finally { 126 if (pStemt != null) { 127 try { 128 pStemt.close(); 129 closeConnection(conn); 130 } catch (SQLException e) { 131 logger.error("getColumnTypes close pstem and connection failure", e); 132 } 133 } 134 } 135 return columnTypes; 136 } 137 /** 138 * 获取表中字段的所有注释 139 * @param tableName 140 * @return 141 */ 142 public static List<String> getColumnComments(String tableName) { 143 List<String> columnTypes = new ArrayList<>(); 144 //与数据库的连接 145 Connection conn = getConnection(); 146 PreparedStatement pStemt = null; 147 String tableSql = SQL + tableName; 148 List<String> columnComments = new ArrayList<>();//列名注释集合 149 ResultSet rs = null; 150 try { 151 pStemt = conn.prepareStatement(tableSql); 152 rs = pStemt.executeQuery("show full columns from " + tableName); 153 while (rs.next()) { 154 columnComments.add(rs.getString("Comment")); 155 } 156 } catch (SQLException e) { 157 e.printStackTrace(); 158 } finally { 159 if (rs != null) { 160 try { 161 rs.close(); 162 closeConnection(conn); 163 } catch (SQLException e) { 164 logger.error("getColumnComments close ResultSet and connection failure", e); 165 } 166 } 167 } 168 return columnComments; 169 } 170 public static void main(String[] args) { 171 List<String> tableNames = getTableNames(); 172 System.out.println("tableNames:" + tableNames); 173 for (String tableName : tableNames) { 174 System.out.println("================start=========================="); 175 System.out.println("=============================================="); 176 System.out.println("ColumnNames:" + getColumnNames(tableName)); 177 System.out.println("ColumnTypes:" + getColumnTypes(tableName)); 178 System.out.println("ColumnComments:" + getColumnComments(tableName)); 179 System.out.println("=============================================="); 180 System.out.println("=================end======================="); 181 } 182 } 183 }

浙公网安备 33010602011771号