jdbc辅助工具

对jdbc链接,关闭进行了封装,同时对操作数据库进行更行操作以及查询进行了封装,使得以后在DAO操作中,代码更简洁,实现了高内聚,低耦合。

DBUtils

包含以下功能

 1.获取链接
 2.关闭资源
 3.执行通用的更新操作
 4.执行通用的查询列表操作
 5.执行通用的查询单条记录操作


/**
 * 通用数据库工具类,基于Druid链接池实现
 * @author LL
 *包含以下功能:
 *1.获取链接
 *2.关闭资源
 *3.执行通用的更新操作
 *4.执行通用的查询列表操作
 *5.执行通用的查询单条记录操作
 */
public class DBUtils {

	// 声明druid连接池对象
		private static DruidDataSource pool;
		/** 数据库连接URL地址**/
		private static String url;
		/**账号**/
		private static String username;
		/**密码**/
		private static String password;
		/**初始连接数 **/
		private static int initialSize;
		/**最大链接数 **/
		private static int maxActive;
		private static int minIdle;
		private static long maxWait;
		private static String fileName = "jdbc.properties";

		static {
			init();
		}

		private static void loadProp(String propName){
			fileName = propName;
			try {
				//属性文件位于src根目录 
				InputStream is = DBUtils.class.getClassLoader().getResourceAsStream(fileName);
				Properties p = new Properties();
				p.load(is);
				
				url = p.getProperty("jdbc.url");
				username = p.getProperty("jdbc.username");
				password = p.getProperty("jdbc.password");
				
				initialSize = Integer.parseInt(p.getProperty("initialSize"));
				maxActive = Integer.parseInt(p.getProperty("maxActive"));
				minIdle = Integer.parseInt(p.getProperty("minIdle"));
				maxWait = Long.parseLong(p.getProperty("maxWait"));
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		private static void init() {
			pool = new DruidDataSource();
			loadProp(fileName);
			pool.setUrl(url);
			pool.setUsername(username);
			pool.setPassword(password);
			// 设置连接池中初始连接数
			pool.setInitialSize(initialSize);
			// 设置最大连接数
			pool.setMaxActive(maxActive);
			// 设置最小闲置链接数
			pool.setMinIdle(minIdle);
			// 设置最大的等待时间(等待获取链接的时间)
			pool.setMaxWait(maxWait);

		}

		/**
		 * 链接获取
		 * @return
		 */
		public static Connection getConn() {
			try {
				if(pool == null || pool.isClosed()){
					init();
				}
				return pool.getConnection();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			return null;
		}
	
	
	public static void close(Statement stmt, Connection conn) {
		try {
			if (stmt != null) {
				stmt.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public static boolean exeUpdate(Connection conn,String sql, Object... obj) {
		PreparedStatement ps = null;
		try {
			conn = getConn();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < obj.length; i++) {
				ps.setObject(i + 1, obj[i]);
			}
			return ps.executeUpdate() > 0;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			close(ps, null);
		}
		return false;
	}

	public static <T> List<T> queryList(Class<T> t, String sql, Object... params) {
		List<T> list = new ArrayList<>();
		T obj = null;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = getConn();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			ResultSet rs = ps.executeQuery();
			//获取插叙结果集中的元数据(获取列类型,数量以及长度等信息)
			ResultSetMetaData rsmd = rs.getMetaData();
			//声明一个map集合,用于临时存储查询到的一条数据(key:列名;value:列值)
			Map<String, Object> map = new HashMap<>();
			//遍历结果集
			while (rs.next()) {
				// 防止缓存上一条数据
				map.clear();
				// 遍历所有的列
				for (int i = 0; i < rsmd.getColumnCount(); i++) {
					//获取列名
					String cname = rsmd.getColumnLabel(i + 1);
					//获取列值
					Object value = rs.getObject(cname);
					//将列明与列值存储到map中
					map.put(cname, value);
				}
				// 利用反射将map中的数据注入到java对象中,并将对象存入集合;
				if (!map.isEmpty()) {
					//获取map集合键集(列名集合)
					Set<String> columnNames = map.keySet();
					//创建对象
					obj = t.newInstance();
					for (String column : columnNames) {
						//根据键获取值
						Object value = map.get(column);
						//获取属性对象
						Field f = t.getDeclaredField(column);
						//设置属性为可访问状态
						f.setAccessible(true);
						//为属性设置
						f.set(obj, value);
					}
					list.add(obj);
				}
			}
		} catch (SQLException | NoSuchFieldException | SecurityException | InstantiationException
				| IllegalAccessException e) {
			e.printStackTrace();
		}
		return list;
	}

	
	public static <T> T queryOne(Class<T> t, String sql, Object... params) {
		T obj = null;
		Connection conn = null;
		PreparedStatement ps = null;
		try {
			conn = getConn();
			ps = conn.prepareStatement(sql);
			for (int i = 0; i < params.length; i++) {
				ps.setObject(i + 1, params[i]);
			}
			ResultSet rs = ps.executeQuery();
			//获取插叙结果集中的元数据(获取列类型,数量以及长度等信息)
			ResultSetMetaData rsmd = rs.getMetaData();
			//声明一个map集合,用于临时存储查询到的一条数据(key:列名;value:列值)
			Map<String, Object> map = new HashMap<>();
			//遍历结果集
			while (rs.next()) {
				// 防止缓存上一条数据
				map.clear();
				// 遍历所有的列
				for (int i = 0; i < rsmd.getColumnCount(); i++) {
					//获取列名
					String cname = rsmd.getColumnName(i + 1);
					//获取列值
					Object value = rs.getObject(cname);
					//将列明与列值存储到map中
					map.put(cname, value);
				}
				// 利用反射将map中的数据注入到java对象中,并将对象存入集合;
				if (!map.isEmpty()) {
					//获取map集合键集(列名集合)
					Set<String> columnNames = map.keySet();
					//创建对象
					obj = t.newInstance();
					for (String column : columnNames) {
						//根据键获取值
						Object value = map.get(column);
						//获取属性对象
						Field f = t.getDeclaredField(column);
						//设置属性为可访问状态
						f.setAccessible(true);
						//为属性设置
						f.set(obj, value);
					}
				}
			}
		} catch (SQLException | NoSuchFieldException | SecurityException | InstantiationException
				| IllegalAccessException e) {
			e.printStackTrace();
		}
		return obj;
	}
	

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值