ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

阿里的开源连接池框架druid的使用

2022-02-07 21:34:15  阅读:156  来源: 互联网

标签:数据源 druid prop getLogger 开源 debug Logger 连接池


文章目录

Jdbc 的不足

jdbc:java和数据库的桥梁

步骤:

  • 注册驱动 Class.forName()—>一次
  • 建立连接 Connection —>每一次
  • 预处理对象PreparedStatement
    • Statement对象 sql拼接—>SQL注入漏洞
    • PreparedStatement对象
      • public interface PreparedStatement extends Statement
  • 执行SQL
  • 关闭连接—>每一次
    建立连接(消耗资源) 关闭连接(释放资源)

数据连接池(DBCP)

  1. 定义好连接数
  2. 从连接池查找是否有空闲连接
  3. 使用空闲连接
  4. 放回池子中

数据源框架(druid)

阿里巴巴的开源连接池框架

使用流程

  1. 创建druid.properties配置文件
druid.driver = com.mysql.cj.jdbc.Driver
druid.url = jdbc:mysql://localhost:3306/mvc_db?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
druid.username=root
druid.password=1234
  1. 使用Properties对象,读取配置文件
// 用来解析properties文件
	private static class DruidPropertiesConfig {

		void load() {
			try {
				// 得到配置文件的路径
				String path = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
				 String fileName = path + "com/dyit/vrius/resources/druid.properties";
				//String fileName = "D:\\sts-workspace\\vuris-sys\\src\\com\\dyit\\vrius\\resources\\druid.properties";

				Properties prop = new Properties();

				prop.load(new FileReader(fileName));

				JdbcUtil.prop = prop;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.getLogger(this.getClass()).debug(e.getMessage());
			}

		}

	}
  1. 引入druid.jar包(jar包放在文末),然后创建数据数据源对象DruidDataSource
// 私有化构造方法 采用双检模式来创建单例
	private JdbcUtil() {
		// 首先加载配置文件
		new DruidPropertiesConfig().load();
		// 得到数据源对象
		ds = new DruidDataSource();
		// 加载配置文件
		ds.configFromPropety(prop);
		Logger.getLogger(this.getClass()).debug("数据源配置成功");
	}
  1. 建立连接
public static void connect() {
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			Logger.getLogger(JdbcUtil.class).debug(e.getMessage());
			e.printStackTrace();
		}

	}

jdbc–> 封装(static)–>properties(配置文件)–>数据源(dbcp)–>单例

完整代码

package com.dyit.vrius.util;

/*
 * 对数据库操作进行封装
 */
import java.io.FileReader;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.log4j.Logger;

import com.alibaba.druid.pool.DruidDataSource;

//创建单例模式
public class JdbcUtil {

	// 创建Propertise对象以便于创建数据源
	private static Properties prop;
	// 私有化类实例 创建单例模式
	private static JdbcUtil instance = null;
	// 创建数据源
	private DruidDataSource ds;
	// 创建数据库链接对象
	private Connection conn;
	// 创建面板对象
	private PreparedStatement prep;
	// 创建resultset集合
	private ResultSet rs;

	// 用来解析properties文件
	private static class DruidPropertiesConfig {

		void load() {
			try {
				// 得到配置文件的路径
				String path = Thread.currentThread().getContextClassLoader().getResource("").toURI().getPath();
				 String fileName = path + "com/dyit/vrius/resources/druid.properties";
				//String fileName = "D:\\sts-workspace\\vuris-sys\\src\\com\\dyit\\vrius\\resources\\druid.properties";

				Properties prop = new Properties();

				prop.load(new FileReader(fileName));

				JdbcUtil.prop = prop;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				Logger.getLogger(this.getClass()).debug(e.getMessage());
			}

		}

	}

	// 私有化构造方法 采用双检模式来创建单例
	private JdbcUtil() {
		// 首先加载配置文件
		new DruidPropertiesConfig().load();
		// 得到数据源对象
		ds = new DruidDataSource();
		// 加载配置文件
		ds.configFromPropety(prop);
		Logger.getLogger(this.getClass()).debug("数据源配置成功");
	}

	public static JdbcUtil getInstance() {
		if (instance == null) {
			synchronized (JdbcUtil.class) {
				if (instance == null) {
					instance = new JdbcUtil();
				}
			}
		}

		return instance;
	}

	// 建立链接
	public void connect() {
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			Logger.getLogger(this.getClass()).debug(e.getMessage());
			e.printStackTrace();
		}

	}

	// 得到preparedStatment面板
	public void preparedStatment(String sql, Object... vals) {
		try {
			prep = conn.prepareStatement(sql);
			for (int i = 0; i < vals.length; i++) {
				prep.setObject(i + 1, vals[i]);
			}
		} catch (SQLException e) {
			Logger.getLogger(this.getClass()).debug(e.getMessage());
			e.printStackTrace();
		}
	}

	// 执行语句
	public void executeUpdate() {
		try {
			prep.executeUpdate();
		} catch (SQLException e) {
			Logger.getLogger(this.getClass()).debug(e.getMessage());
			e.printStackTrace();
		}
	}

	// 查询语句
	public ResultSet executeQuery() {
		try {
			rs = prep.executeQuery();
		} catch (SQLException e) {
			Logger.getLogger(this.getClass()).debug(e.getMessage());
			e.printStackTrace();
		}
		return rs;
	}

	// 关闭链接
	public void close() {
		try {
			if (rs != null) {
				rs.close();
			}
			if (prep != null) {
				prep.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (Exception e) {
			Logger.getLogger(this.getClass()).debug(e.getMessage());
			e.printStackTrace();
		}
	}

}

jar包连接

链接:https://pan.baidu.com/s/1F0BVqHAd3ABJ9DijMLzGPw 
提取码:88u9

标签:数据源,druid,prop,getLogger,开源,debug,Logger,连接池
来源: https://blog.csdn.net/qq_45795744/article/details/122814780

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有