数据库直连提示 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 小时前
破解gh-ost变更导致MySQL表膨胀之谜|得物技术
数据库·后端·mysql
Raymond运维5 小时前
MariaDB源码编译安装(二)
运维·数据库·mariadb
沢田纲吉6 小时前
🗄️ MySQL 表操作全面指南
数据库·后端·mysql
RestCloud21 小时前
SQL Server到Hive:批处理ETL性能提升30%的实战经验
数据库·api
RestCloud21 小时前
为什么说零代码 ETL 是未来趋势?
数据库·api
ClouGence1 天前
CloudCanal + Paimon + SelectDB 从 0 到 1 构建实时湖仓
数据库
DemonAvenger1 天前
NoSQL与MySQL混合架构设计:从入门到实战的最佳实践
数据库·mysql·性能优化
AAA修煤气灶刘哥2 天前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
RestCloud2 天前
揭秘 CDC 技术:让数据库同步快人一步
数据库·api
得物技术2 天前
MySQL单表为何别超2000万行?揭秘B+树与16KB页的生死博弈|得物技术
数据库·后端·mysql