Druid
jar包下载
进入官网 https://repo1.maven.org/maven2/com/alibaba/druid/
选择版本,单击进入
选择jar包(.jar)
实现步骤
- 导入jar包
- 定义配置文件
(1)是properties形式的
(2)可以叫做任意名称,可以放在任意目录下 - 加载配置文件 Properties
- 获取数据库连接池:通过工厂类来获取 DruidDataSourceFactory
- 获取连接:getConnection
配置文件
driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/jdbc username=root password=root initialSize=5 maxActive=10 maxWait=3000
package druid; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.io.InputStream; import java.sql.Connection; import java.util.Properties; public class DruidDemo { public static void main(String[] args) throws Exception { //加载配置文件 Properties pro = new Properties(); InputStream is = DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"); pro.load(is); //获取连接池对象 DataSource ds = DruidDataSourceFactory.createDataSource(pro); //获取连接 Connection conn = ds.getConnection(); System.out.println(conn); } }
工具类
- 定义JDBCUtils
- 提供静态代码块加载配置文件,初始化连接池对象
- 提供方法
(1)获取连接方法:通过数据库连接池获取连接
(2)释放资源
(3)获取连接池
package druid.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax.sql.DataSource; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; public class JDBCUtils { //定义成员变量 private static DataSource ds; static { //加载配置文件 Properties pro = new Properties(); try { pro.load(JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties")); ds = DruidDataSourceFactory.createDataSource(pro); } catch (Exception e) { e.printStackTrace(); } } //获取连接 public static Connection getConnection() throws SQLException { return ds.getConnection(); } //释放资源 public static void close(Statement stmt, Connection conn){ if (stmt != null){ try { stmt.close(); } catch (Exception e) { e.printStackTrace(); } } if (conn != null){ try { conn.close(); } catch (Exception e) { e.printStackTrace(); } } } public static void close(ResultSet rs, Statement stmt, Connection conn){ if (rs != null){ try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } close(stmt, conn); } //获取连接池 public static DataSource getDataSource(){ return ds; } }