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

相关推荐
SAP上海工博云署12 分钟前
2026年中小企业SAP服务商选型技术解析
大数据·运维·数据库·人工智能·信息可视化·运维开发·信息与通信
RestCloud13 分钟前
版本迭代丨谷云科技ETLCloud V4.2版本更新速览
数据库·doris·etl·etlcloud·数据集成平台·datahub·ftp处理
Adair_z23 分钟前
[SEO艺术重读] 第13篇 SEO教育与研究
java·网络·数据库
不爱吃糖の糖糖27 分钟前
RAG 04:向量数据库与索引算法
数据库·算法
逍遥德30 分钟前
PostgreSQL --- JSON 函数详解
数据库·sql·postgresql·json
Larcher30 分钟前
后续:上次的优化又崩了?这次是 SQLite WAL 把 Codex 直接卡死了
数据库·人工智能·github
小马爱打代码35 分钟前
MySQL高可用与扩展:主从复制、读写分离、分库分表
服务器·数据库·mysql
m0_7408596236 分钟前
Docker安装常见数据库命令汇总(2026)
数据库·docker·容器
j7~41 分钟前
【MYSQL】 复合查询--详解(重点)
数据库·mysql·子查询·多表查询·自链接·合并查询
睡不醒男孩03082341 分钟前
PostgreSQL 高可用怎么做?我为什么选择了 CLup
数据库·postgresql