数据库直连提示 No suitable driver found for jdbc:postgresql

背景:我在代码里使用直连的方式在数据库中创建数据库等,由于需要适配各个数据库服务所以我分别兼容了mysql、postgresql、oracal等。但是在使用过程中会出现错误:

No suitable driver found for jdbc:postgresql

但是我再使用mysql的直连方式创建方式时没有出现问题。

代码如下:

java 复制代码
 Connection connection = null;
        Statement statement = null;
        try {
            connection = DriverManager.getConnection(url, loginUser, loginPwd);
            statement = connection.createStatement();
            //其他代码
        } catch (Exception e){
            LOGGER.error("创建数据库信息异常", e);
            result = false;
        } finally {
            close(connection, statement);
        }

出现这个的一个原因是没有 postgresql 依赖。所以我先将依赖加入:

复制代码
<dependency>
    <groupId>org.postgresql</groupId>
    <artifactId>postgresql</artifactId>
</dependency>

但是在之后的运行中还是提示这个错误。经过排查发现DriverManager中的driver列表只有mysql的Driver。没有postgresql的Driver。但是这个Driver的注册都是在类初始化的时候自动注册的:

所以不知道为什么他没有注册到DriverManager里面。

解决办法是我们在任意的一个地方创建一下我们需要的Driver。例如postgresql的:

java 复制代码
 Connection connection = null;
Statement statement = null;
        try {
            Class clazz = Class.forName("org.postgresql.Driver");
            clazz.newInstance();
            connection = DriverManager.getConnection(url, loginUser, loginPwd);
            statement = connection.createStatement();
            //其他代码
        } catch (Exception e){
            LOGGER.error("创建数据库信息异常", e);
            result = false;
        } finally {
            close(connection, statement);
        }

这样就会自动执行其中的静态代码块,实现注册Driver到DriverManager的目的。

相关推荐
华科易迅1 小时前
Spring 事务(注解)
java·数据库·spring
Java面试题总结1 小时前
MySQL篇 索引失效
数据库·mysql
last demo2 小时前
mysql
运维·数据库·mysql·oracle
kevin_cat3 小时前
oracle 扩展表空间
数据库·oracle
花间相见4 小时前
【MySQL面试题】—— MySQL面试高频问题汇总:从原理到实战,覆盖90%考点
数据库·mysql·面试
高梦轩4 小时前
MySQL 数据库备份与恢复
数据库·oracle
一直都在5724 小时前
Redis(二)
数据库·redis·缓存
TDengine (老段)5 小时前
TDengine IDMP 工业数据建模 —— 属性
大数据·数据库·人工智能·时序数据库·tdengine·涛思数据
爱丽_6 小时前
Redis 分布式锁:SET NX、过期时间、续租、可重入、Redlock 与坑
数据库·redis·分布式
IT小崔6 小时前
SqlSugar 使用教程
数据库·后端