postgresql 臭名昭著的 java.sql.SQLException:找不到合适的驱动程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1911253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-10 22:23:58  来源:igfitidea点击:

The infamous java.sql.SQLException: No suitable driver found

postgresqltomcatjdbcgeoserver

提问by Rick Wayne

I'm trying to add a database-enabled JSP to an existing Tomcat 5.5 application (GeoServer 2.0.0, if that helps).

我正在尝试将启用数据库的 JSP 添加到现有的 Tomcat 5.5 应用程序(GeoServer 2.0.0,如果有帮助)。

The app itself talks to Postgres just fine, so I know that the database is up, user can access it, all that good stuff. What I'm trying to do is a database query in a JSP that I've added. I've used the config example in the Tomcat datasource examplepretty much out of the box. The requisite taglibs are in the right place -- no errors occur if I just have the taglib refs, so it's finding those JARs. The postgres jdbc driver, postgresql-8.4.701.jdbc3.jar is in $CATALINA_HOME/common/lib.

该应用程序本身与 Postgres 对话得很好,所以我知道数据库已启动,用户可以访问它,所有这些好东西。我想要做的是在我添加的 JSP 中进行数据库查询。我已经开箱即用地使用了Tomcat 数据源示例中的配置示例。必需的 taglib 位于正确的位置——如果我只有 taglib 引用,则不会发生错误,因此它正在查找那些 JAR。postgres jdbc 驱动程序 postgresql-8.4.701.jdbc3.jar 位于 $CATALINA_HOME/common/lib 中。

Here's the top of the JSP:

这是 JSP 的顶部:

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<sql:query var="rs" dataSource="jdbc/mmas">
  select current_validstart as ValidTime from runoff_forecast_valid_time
</sql:query>

The relevant section from $CATALINA_HOME/conf/server.xml, inside the <Host>which is in turn within <Engine>:

来自 $CATALINA_HOME/conf/server.xml 的相关部分,在里面<Host>依次是<Engine>

<Context path="/gs2" allowLinking="true">
  <Resource name="jdbc/mmas" type="javax.sql.Datasource"
      auth="Container" driverClassName="org.postgresql.Driver"
      maxActive="100" maxIdle="30" maxWait="10000"
      username="mmas" password="very_secure_yess_precious!"
      url="jdbc:postgresql//localhost:5432/mmas" />
</Context>

These lines are the last in the tag in webapps/gs2/WEB-INF/web.xml:

这些行是 webapps/gs2/WEB-INF/web.xml 中标记的最后一行:

<resource-ref>
  <description>
     The database resource for the MMAS PostGIS database
  </description>
  <res-ref-name>
     jdbc/mmas
  </res-ref-name>
  <res-type>
     javax.sql.DataSource
  </res-type>
  <res-auth>
     Container
  </res-auth>
</resource-ref>

Finally, the exception:

最后,例外:

   exception
    org.apache.jasper.JasperException: Unable to get connection, DataSource invalid: "java.sql.SQLException: No suitable driver"
    [...wads of ensuing goo elided]

回答by BalusC

The infamous java.sql.SQLException: No suitable driver found

臭名昭著的 java.sql.SQLException:找不到合适的驱动程序

This exception can have basically twocauses:

这个异常基本上有两个原因:

1. JDBC driver is not loaded

1. JDBC驱动未加载

You need to ensure that the JDBC driver is placed in server's own /libfolder.

您需要确保 JDBC 驱动程序放在服务器自己的/lib文件夹中。

Or, when you're actually not using a server-managed connection pool data source, but are manually fiddling around with DriverManager#getConnection()in WAR, then you need to place the JDBC driver in WAR's /WEB-INF/liband perform ..

或者,当您实际上没有使用服务器管理的连接池数据源,而是DriverManager#getConnection()在 WAR中手动摆弄时,那么您需要将 JDBC 驱动程序放在 WAR 中/WEB-INF/lib并执行 ..

Class.forName("com.example.jdbc.Driver");

.. in your code beforethe first DriverManager#getConnection()call whereby you make sure that you do notswallow/ignore any ClassNotFoundExceptionwhich can be thrown by it and continue the code flow as if nothing exceptional happened. See also Where do I have to place the JDBC driver for Tomcat's connection pool?

.. 在您第一次调用之前的代码中DriverManager#getConnection()确保您不会吞下/忽略任何ClassNotFoundException可能被它抛出的内容,并继续代码流程,就好像没有发生任何异常一样。另请参阅我必须在哪里放置 Tomcat 连接池的 JDBC 驱动程序?

2. Or, JDBC URL is in wrong syntax

2. 或者,JDBC URL 的语法错误

You need to ensure that the JDBC URL is conform the JDBC driver documentation and keep in mind that it's usually case sensitive. When the JDBC URL does not return truefor Driver#acceptsURL()for any of the loaded drivers, then you will also get exactly this exception.

您需要确保 JDBC URL 符合 JDBC 驱动程序文档,并记住它通常区分大小写。当JDBC URL不会返回true用于Driver#acceptsURL()对任何加载的驱动程序,那么你也将获得正是这种例外。

In case of PostgreSQLit is documented here.

PostgreSQL 的情况下,它被记录在这里

With JDBC, a database is represented by a URL (Uniform Resource Locator). With PostgreSQL?, this takes one of the following forms:

  • jdbc:postgresql:database
  • jdbc:postgresql://host/database
  • jdbc:postgresql://host:port/database

使用 JDBC,数据库由 URL(统一资源定位器)表示。对于 PostgreSQL?,这采用以下形式之一:

  • jdbc:postgresql:database
  • jdbc:postgresql://host/database
  • jdbc:postgresql://host:port/database

In case of MySQLit is documented here.

MySQL 的情况下,它被记录在这里

The general format for a JDBC URL for connecting to a MySQL server is as follows, with items in square brackets ([ ]) being optional:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] ? [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

用于连接 MySQL 服务器的 JDBC URL 的一般格式如下,方括号 ( [ ]) 中的项目是可选的:

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] ? [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]

In case of Oracleit is documented here.

Oracle 的情况下,它被记录在这里

There are 2 URL syntax, old syntax which will only work with SID and the new one with Oracle service name.

Old syntax jdbc:oracle:thin:@[HOST][:PORT]:SID

New syntax jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE

有两种 URL 语法,旧语法仅适用于 SID,新语法适用于 Oracle 服务名称。

旧语法 jdbc:oracle:thin:@[HOST][:PORT]:SID

新语法 jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE



See also:

也可以看看:

回答by araqnid

url="jdbc:postgresql//localhost:5432/mmas"

That URL looks wrong, do you need the following?

该 URL 看起来不对,您需要以下内容吗?

url="jdbc:postgresql://localhost:5432/mmas"

回答by Vinayak Singh

I faced the similar issue. My Project in context is Dynamic Web Project(Java 8 + Tomcat 8) and error is for PostgreSQL Driver exception: No suitable driver found

我遇到了类似的问题。上下文中的我的项目是动态 Web 项目(Java 8 + Tomcat 8),错误是针对 PostgreSQL 驱动程序异常:找不到合适的驱动程序

It got resolved by adding Class.forName("org.postgresql.Driver")before calling getConnection()method

它通过Class.forName("org.postgresql.Driver")在调用getConnection()方法之前添加来解决

Here is my Sample Code:

这是我的示例代码:

try {
            Connection conn = null;
            Class.forName("org.postgresql.Driver");
            conn = DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/?preferQueryMode="
                    + sql_auth,sql_user , sql_password);
        } catch (Exception e) {
            System.out.println("Failed to create JDBC db connection " + e.toString() + e.getMessage());
        }

回答by Manuel Schmitzberger

I've forgot to add the PostgreSQL JDBC Driver into my project (Mvnrepository).

我忘了将 PostgreSQL JDBC 驱动程序添加到我的项目 ( Mvnrepository) 中。

Gradle:

摇篮

// http://mvnrepository.com/artifact/postgresql/postgresql
compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'

Maven:

马文

<dependency>
    <groupId>postgresql</groupId>
    <artifactId>postgresql</artifactId>
    <version>9.0-801.jdbc4</version>
</dependency>

You can also downloadthe JARand import to your project manually.

您也可以下载JAR手动和导入到项目中。

回答by A Venkatraman

I found the followig tip helpful, to eliminate this issue in Tomcat -

我发现以下提示很有帮助,可以消除 Tomcat 中的这个问题 -

be sure to load the driver first doing a Class.forName(" org.postgresql.Driver"); in your code.

确保首先加载驱动程序执行 Class.forName(" org.postgresql.Driver"); 在你的代码中。

This is from the post - https://www.postgresql.org/message-id/[email protected]

这是来自帖子 - https://www.postgresql.org/message-id/[email protected]

The jdbc code worked fine as a standalone program but, in TOMCAT it gave the error -'No suitable driver found'

jdbc 代码作为独立程序运行良好,但在 TOMCAT 中它给出了错误 -'找不到合适的驱动程序'

回答by ankkol2011

A very silly mistake which could be possible resulting is adding of space at the start of the JDBC URL connection.

一个可能导致的非常愚蠢的错误是在 JDBC URL 连接的开头添加空间。

What I mean is:-

我的意思是:-

suppose u have bymistake given the jdbc url like

假设你错误地给出了 jdbc url,例如

String jdbcUrl=" jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimeZone=UTC";

(Notice there is a space in the staring of the url, this will make the error)

(注意url的起始位置有一个空格,这会导致错误)

the correct way should be:

正确的方法应该是:

String jdbcUrl="jdbc:mysql://localhost:3306/web_customer_tracker?useSSL=false&serverTimeZone=UTC";

(Notice no space in the staring, you may give space at the end of the url but it is safe not to)

(注意注视中没有空格,您可以在 url 的末尾留出空格,但不这样做是安全的)

回答by user7994072

It might be worth noting that this can also occur when Windows blocks downloads that it considers to be unsafe. This can be addressed by right-clicking the jar file (such as ojdbc7.jar), and checking the 'Unblock' box at the bottom.

可能值得注意的是,当 Windows 阻止它认为不安全的下载时,也会发生这种情况。这可以通过右键单击 jar 文件(例如 ojdbc7.jar)并选中底部的“取消阻止”框来解决。

Windows JAR File Properties Dialog:
Windows JAR File Properties Dialog

Windows JAR 文件属性对话框
Windows JAR 文件属性对话框

回答by feistyfawn

As well as adding the MySQL JDBC connector ensure the context.xml (if not unpacked in the Tomcat webapps folder) with your DB connection definitions are included within Tomcats conf directory.

除了添加 MySQL JDBC 连接器外,还要确保具有数据库连接定义的 context.xml(如果未在 Tomcat webapps 文件夹中解压)包含在 Tomcats conf 目录中。

回答by Ryan D

I had this exact issue when developing a Spring Boot application in STS, but ultimately deploying the packaged war to WebSphere(v.9). Based on previous answers my situation was unique. ojdbc8.jar was in my WEB-INF/lib folder with Parent Last class loading set, but always it says it failed to find the suitable driver.

我在 STS 中开发 Spring Boot 应用程序时遇到了这个确切的问题,但最终将打包的 war 部署到 WebSphere(v.9)。根据以前的答案,我的情况是独一无二的。ojdbc8.jar 在我的 WEB-INF/lib 文件夹中,并设置了 Parent Last class loading,但它总是说找不到合适的驱动程序。

My ultimate issue was that I was using the incorrect DataSource class because I was just following along with online tutorials/examples. Found the hint thanks to David Dai comment on his own question here: Spring JDBC Could not load JDBC driver class [oracle.jdbc.driver.OracleDriver]

我的最终问题是我使用了不正确的 DataSource 类,因为我只是按照在线教程/示例进行操作。感谢 David Dai 在这里对他自己的问题的评论找到了提示:Spring JDBC 无法加载 JDBC 驱动程序类 [oracle.jdbc.driver.OracleDriver]

Also later found spring guru example with Oracle specific driver: https://springframework.guru/configuring-spring-boot-for-oracle/

后来还找到了带有 Oracle 特定驱动程序的 spring guru 示例:https: //springframework.guru/configuring-spring-boot-for-oracle/

Example that throws error using org.springframework.jdbc.datasource.DriverManagerDataSourcebased on generic examples.

使用org.springframework.jdbc.datasource.DriverManagerDataSource基于通用示例引发错误的示例。

@Config
@EnableTransactionManagement
public class appDataConfig {
 \* Other Bean Defs *\
    @Bean
    public DataSource dataSource() {
        // configure and return the necessary JDBC DataSource
        DriverManagerDataSource dataSource = new DriverManagerDataSource("jdbc:oracle:thin:@//HOST:PORT/SID", "user", "password");
        dataSource.setSchema("MY_SCHEMA");
        return dataSource;
    }
}

And the corrected exapmle using a oracle.jdbc.pool.OracleDataSource:

并使用以下更正示例oracle.jdbc.pool.OracleDataSource

@Config
@EnableTransactionManagement
public class appDataConfig {
/* Other Bean Defs */
@Bean
    public DataSource dataSource() {
        // configure and return the necessary JDBC DataSource
        OracleDataSource datasource = null;
        try {
            datasource = new OracleDataSource();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        datasource.setURL("jdbc:oracle:thin:@//HOST:PORT/SID");
        datasource.setUser("user");
        datasource.setPassword("password");

        return datasource;
    }
}

回答by Jerry

I encountered this issue by putting a XML file into the src/main/resourceswrongly, I deleted it and then all back to normal.

我遇到了这个问题,把一个 XML 文件src/main/resources错误地放入了,我删除了它,然后一切恢复正常。