数据库直连提示 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的目的。

相关推荐
zhaoyong22233 分钟前
MySQL 存储过程中字符集与排序规则不匹配导致查询性能下降的解决方案
jvm·数据库·python
sinat_3834373634 分钟前
golang如何从Python转型Go开发_golang从Python转型Go开发攻略
jvm·数据库·python
远洪35 分钟前
claude code 国内安装使用
数据库·mysql
雨辰AI38 分钟前
SpringBoot3 + 人大金仓 V9 微服务监控实战|Prometheus+Grafana+SkyWalking 全链路监控
数据库·后端·微服务·grafana·prometheus·skywalking
二哈赛车手39 分钟前
新人笔记---ES和kibana启动问题以及一些常用的linux的错误排查方法,以及ES,数据库泄密解决方案[超详细]
java·linux·数据库·spring boot·笔记·elasticsearch
myrh pdmd40 分钟前
maven导入spring框架
数据库·spring·maven
爬山算法1 小时前
MongoDB(118)如何在升级过程中进行数据备份?
数据库·mongodb·oracle
千月落2 小时前
Redis数据迁移
数据库·redis·缓存
wangbing11253 小时前
MySQL 官方 GPG 密钥过期问题
数据库·mysql
PaperData3 小时前
2000-2023年地级市数字基础设施评价指标体系
大数据·网络·数据库·人工智能·数据分析·经管