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


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

    No suitable driver found for jdbc:postgresql

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

    代码如下:

    1. Connection connection = null;
    2. Statement statement = null;
    3. try {
    4. connection = DriverManager.getConnection(url, loginUser, loginPwd);
    5. statement = connection.createStatement();
    6. //其他代码
    7. } catch (Exception e){
    8. LOGGER.error("创建数据库信息异常", e);
    9. result = false;
    10. } finally {
    11. close(connection, statement);
    12. }

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

    
        org.postgresql
        postgresql
    

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

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

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

    1. Connection connection = null;
    2. Statement statement = null;
    3. try {
    4. Class clazz = Class.forName("org.postgresql.Driver");
    5. clazz.newInstance();
    6. connection = DriverManager.getConnection(url, loginUser, loginPwd);
    7. statement = connection.createStatement();
    8. //其他代码
    9. } catch (Exception e){
    10. LOGGER.error("创建数据库信息异常", e);
    11. result = false;
    12. } finally {
    13. close(connection, statement);
    14. }

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

  • 相关阅读:
    【MySQL基础|第三篇】--- 详谈SQL中的DQL语句
    模仿Spring注入接口的代理类全过程
    P2602数字计数
    C++中map和set的区别
    探索Java设计模式:桥接模式
    postgresql中的stringtype=unspecified有什么作用?
    windows安装mysql5.7.35
    iOS提词器,画中画
    华清远见-JavaWeb学习总结
    python gui(六)全局设定
  • 原文地址:https://blog.csdn.net/qq_34484062/article/details/132811972