Druid数据库连接池连接方式最细详解

方式1:使用druid工厂初始化连接池

具体步骤:

    导入druid的jar包 导入mysql的连接驱动 在代码块中完成数据源的初始化
public class Utils { private static DataSource dataSource; static { //方式1:通过的druid工厂创建数据源 //创建输入流 InputStream stream = Utils.class.getClassLoader().getResourceAsStream("jdbc.properties"); Properties properties = new Properties(); try { //将配置文件中的信息加载到properties中 properties.load(stream); //创建druid数据连接池,并完成数据池的初始化 dataSource = DruidDataSourceFactory.createDataSource(properties); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { //如果连接出现异常,则抛出一个运行时异常 throw new RuntimeException("连接池出现异常."); } } }

方式2:先创建一个druidDatasouurce,后面手动完成数据源的初始化

public class Utils { private static DruidDataSource druidDataSource; static { try { //方式2:通过创建一个druidDatasouurce,后面手动完成数据源的初始化 druidDataSource=new DruidDataSource(); druidDataSource.setDriverClassName("com.mysql.cj.jdbc.Driver"); druidDataSource.setUrl("jdbc:mysql://localhost:3306/bookdb?serverTimezone=UTC"); druidDataSource.setUsername("root"); druidDataSource.setPassword("hjl123"); //可选设置 druidDataSource.setMaxActive(20); druidDataSource.setInitialSize(10); druidDataSource.setMaxWait(5000); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection2() { try { return druidDataSource.getConnection(); } catch (SQLException e) { //如果连接出现异常,则抛出一个运行时异常 throw new RuntimeException("连接池出现异常."); } } }

测试结果:

Properties文件:

driverClassName=com.mysql.cj.jdbc.Driver url=jdbc:mysql://localhost:3306/bookdb?serverTimezone=UTC username=root password=hjl123 initialSize=10 maxActive=15 minIdle=5 maxWait=5000

需要注意的细节(重点):

细节1:

在第二步导入的mysql驱动中,需要根据自己的数据库版本来选取。当前主流的有二个版本,一个是5.7左右的,一个是8.0左右的。我自己的mysql数据库是8.0版的,所以我需要使用8.0以上的mysql数据驱动。如果版本选不对,会报错

细节2:

根据驱动的不同,driverClassName和url属性对应的值也不一样. 5.7版的如下: driverClassName=com.mysql.jdbc.Driver //characterEncoding=utf8数据库此次连接传输UTF8数据,项目为UTF8 数据库为其他编码 url=jdbc:mysql://localhost:3306/books? characterEncoding=utf8 8.0版本如下: driverClassName=com.mysql.cj.jdbc.Driver //serverTimezone=UTC这个必须要加的 url=jdbc:mysql://localhost:3306/bookdb?serverTimezone=UTC

细节3:

mysql 驱动 5.1.6 以后可以无需 Class.forName(“com.mysql.cj.jdbc.Driver”); 对于driverClassName这个属性是可以省略不写的 。底层会根据驱动版本自动完成驱动注册。

细节4:在使用德鲁伊工厂模式,通过properties文件读取对应的属性时,属性名是固定的,必须一致(一定要注意!!!!!!!!!)。而使用第二种的话就可以更根据自己喜好命名。

最后:如果有哪里不对的地方,望指教!

经验分享 程序员 微信小程序 职场和发展