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

相关推荐
xuzhiqiang072416 分钟前
MySQL——数据库的操作
数据库·mysql·oracle
德迅云安全-小潘30 分钟前
德迅零域(微隔离):破解云时代横向渗透困局的“手术刀”
网络·数据库·安全
敲代码的哈吉蜂34 分钟前
高可用集群Keepalived
运维·服务器·网络·数据库
Dxy12393102161 小时前
在 DrissionPage 中设置代理
数据库
青春:一叶知秋1 小时前
【Redis存储】redis事务
数据库·redis·缓存
v_cxsj8131 小时前
学会写导师都说好的论文——Spring Boot高校实习管理平台18517【部署教程+可完整运行源码+数据库】
数据库·spring boot·实习信息·企业招聘
jjjxxxhhh1233 小时前
[Google Test]- Google Test Ubuntu 完整验证指南
linux·数据库·ubuntu
三无少女指南3 小时前
开发者环境配置:用 Ollama 实现本地大模型部署(附下载慢的解决方案
c语言·开发语言·数据库·ubuntu
Lxinccode4 小时前
AI编程(3) / claude code[3] : 更新apiKey
java·数据库·ai编程·claude code
数据知道4 小时前
MongoDB数据类型全景:String、Number、Date、Boolean 及特殊的 null 类型处理
数据库·mongodb