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

发布于 2024-08-14 09:07:50 字数 1890 浏览 4 评论 0 原文

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

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

这是 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>

$CATALINA_HOME/conf/server.xml 中的相关部分,位于 内,而 内又如下:

<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>

这些行是 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>

最后,例外情况:

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

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

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 example pretty 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.

Here's the top of the 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>:

<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:

<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]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(23

画▽骨i 2024-08-21 09:07:50

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

此异常基本上可能有两个原因:

1. 未加载 JDBC 驱动程序

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

其他服务器也有类似的放置 JAR 文件的方式:

  • GlassFish:将 JAR 文件放入/glassfish/lib
  • WildFly:将 JAR 文件放入 /standalone/deployments

或者,当您实际上不使用服务器管理的连接池数据源,例如通过 JNDI @Resource 获取或在 JPA 的 persistence.xml 中配置,但是当您手动摆弄 DriverManager#getConnection() WAR 中自定义类的低级方式,那么您需要将 JDBC 驱动程序放在 WAR 的 /WEB-INF/lib 中

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

在您的自定义代码中第一个 DriverManager#getConnection() 调用之前执行 .. ..,从而确保您不< /strong> 吞下/忽略它可能引发的任何 ClassNotFoundException 并继续代码流程,就好像没有发生任何异常一样。另请参阅 我在哪里为 Tomcat 的连接池放置 JDBC 驱动程序?向与数据库交互的 Servlet 提交表单会导致空白页面

2. 或者,JDBC URL 语法错误

您需要确保指定的 JDBC URL 符合 JDBC 驱动程序文档,并记住它通常区分大小写。当 JDBC URL 未针对 Driver#acceptsURL() 对于任何加载的驱动程序,那么您也将得到准确的结果这个例外。

对于PostgreSQL,它记录在此处

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

  • jdbc:postgresql:数据库
  • jdbc:postgresql:/
  • jdbc:postgresql://主机/数据库
  • jdbc:postgresql://host/
  • jdbc:postgresql://主机:端口/数据库
  • jdbc:postgresql://host:port/

如果是 MySQL,则记录为 此处

这是连接 URL 的通用格式:

协议//[主机][/数据库][?属性]

这是一个简单的单主机连接 URL 示例:

jdbc:mysql://host1:33060/sakila

如果是 Oracle,则记录为

Thin 驱动程序为所有这些类型提供了以下类型的 URL 格式:

SID(Oracle 不再推荐使用):

jdbc:oracle:thin:[<用户>/<密码>]@<主机>[:<端口>]:

服务:

jdbc:oracle:thin:[<用户>/<密码>]@//<主机>[:<端口>]/<服务>

TNS 名称:

jdbc:oracle:thin:[<用户>/<密码>]@


另请参阅:

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

This exception can have basically two causes:

1. JDBC driver is not loaded

In case of Tomcat, you need to ensure that the JDBC driver is placed in server's own /lib folder.

Other servers have a similar way of placing the JAR file:

  • GlassFish: put the JAR file in /glassfish/lib
  • WildFly: put the JAR file in /standalone/deployments

Or, when you're actually not using a server-managed connection pool data source which you e.g. obtain via JNDI @Resource or configure in JPA's persistence.xml, but when you are manually fiddling around with DriverManager#getConnection() the low level way in a custom class in WAR, then you need instead to place the JDBC driver in WAR's /WEB-INF/lib and perform ..

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

.. in your custom code before the first DriverManager#getConnection() call, whereby you make sure that you do not swallow/ignore any ClassNotFoundException which 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? and Submitting form to Servlet which interacts with database results in blank page.

2. Or, JDBC URL is in wrong syntax

You need to ensure that the specified 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 true for Driver#acceptsURL() for any of the loaded drivers, then you will also get exactly this exception.

In case of PostgreSQL it is documented here.

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:/
  • jdbc:postgresql://host/database
  • jdbc:postgresql://host/
  • jdbc:postgresql://host:port/database
  • jdbc:postgresql://host:port/

In case of MySQL it is documented here.

This is the generic format of the connection URL:

protocol//[hosts][/database][?properties]

This is an example of a simple single-host connection URL:

jdbc:mysql://host1:33060/sakila

In case of Oracle it is documented here.

The Thin driver offers these kinds of URL formats for all of them:

SID (no longer recommended by Oracle to be used):

jdbc:oracle:thin:[<user>/<password>]@<host>[:<port>]:<SID>

Services:

jdbc:oracle:thin:[<user>/<password>]@//<host>[:<port>]/<service>

TNSNames:

jdbc:oracle:thin:[<user>/<password>]@<TNSName>


See also:

此生挚爱伱 2024-08-21 09:07:50

我忘记将 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>

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

I've forgot to add the PostgreSQL JDBC Driver into my project (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 download the JAR and import to your project manually.

满地尘埃落定 2024-08-21 09:07:50
url="jdbc:postgresql//localhost:5432/mmas"

该网址看起来有误,您需要以下内容吗?

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

That URL looks wrong, do you need the following?

url="jdbc:postgresql://localhost:5432/mmas"
╰つ倒转 2024-08-21 09:07:50

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

通过添加 Class.forName("org.postgresql" 解决了这个问题.Driver") 在调用 getConnection() 方法之前

这是我的示例代码:

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());
        }

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

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

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());
        }
辞慾 2024-08-21 09:07:50

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

请务必先加载驱动程序,执行 Class.forName("
org.postgresql.Driver"); 在您的代码中。

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

jdbc 代码运行良好,如下所示一个独立的程序,但是在 TOMCAT 中它给出了错误 -“找不到合适的驱动程序”

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

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

This is from the post - 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'

纵性 2024-08-21 09:07:50

摘要:

  • Soln2(推荐)::

    • 1.将 mysql-connector-java-8.0.28.jar 文件放入 /lib 中。
  • Soln1::

    • 1 .将mysql-connector-java-8.0.28.jar文件放入WEB-INF/lib中。
    • 2.在 Servlet Java 代码中使用 Class.forName("com.mysql.cj.jdbc.Driver");

Soln1 (Ori Ans) //-20220304

简而言之:

  1. 确保 WEB-INF/lib 中有 mysql-connector-java-8.0.28.jar 文件,
  2. 并确保使用 Class.forName("com.mysql.cj.jdbc.Driver");

jar & class for jdbc connect


附加注释(不重要),基于我的尝试(可能是错误的)::

  • 1.1 将 jar 直接放入 Java 构建路径 不起作用

  • 1.2。将jar放入数据管理>中驱动程序定义> MySQL JDBC 驱动程序 >然后将其作为库添加到 Java 构建路径 不起作用。

  • 1.3 =>它必须位于 WEB-INF/lib 内(我不知道为什么)

  • 1.4 使用版本 mysql-connector-java-8.0.28.jar 可以工作, Eclipse 中仅提供版本 5.1 MySQL JDBC Driver 设置无关紧要,忽略它。

    <参见如何使用Eclipse数据库管理视角连接MySql 8.0数据库 >

  •  Class.forName("com.mysql.cj.jdbc.Driver");
        Class.forName("com.mysql.jdbc.Driver");
    

    两部作品,
    Class.forName("com.mysql.jdbc.Driver"); 已弃用。

    正在加载类“com.mysql.jdbc.Driver”。这已被弃用。新的驱动程序类是“com.mysql.cj.jdbc.Driver”。驱动程序通过 SPI 自动注册,通常不需要手动加载驱动程序类。
    

    <参见https://www .yawintutor.com/no-suitable-driver-found-for-jdbcmysql-localhost3306-testdb/ >

  • <块引用>

    如果您想连接到 MySQL 数据库,可以使用名为 Connector/} 的 type-4 驱动程序,该驱动程序可从 MySQL 网站免费获得。但是,该驱动程序通常包含在 Tomcat 的 lib 目录中。因此,您通常不需要从 MySQL 站点下载此驱动程序。

    -- Murach 的 Java Servlet 和 JSP

    我在Tomcat中找不到作者所说的驱动程序,我需要使用mysql-connector-java-8.0.28.jar
    <(删除)请参阅下面更新的答案 soln2>


  • <块引用>

    但是,如果您使用的是旧版本的 Java,则需要在调用 getConnection 方法之前使用 Class 类的 forName 方法显式加载驱动程序

    即使使用 JDBC 4.0,您有时也会收到一条消息:“未找到合适的驱动程序。”在这种情况下,您可以使用 Class 类的 forName 方法显式加载驱动程序。但是,如果自动驱动程序加载有效,则从代码中删除此方法调用通常是有意义的。

    如何加载 JDBC 4.0 之前的 MySQL 数据库驱动程序

    Class.forName{"com.mysql.jdbc.Driver");

    -- Murach 的 Java Servlet 和 JSP

    我必须在我的系统中使用Class.forName("com.mysql.cj.jdbc.Driver");,没有自动类加载。不知道为什么。
    <(删除)请参阅下面更新的答案 soln2>


  • 当我在 Eclipse 中使用普通 Java 项目而不是动态 Web 项目时,

    我只需要将mysql-connector-java-8.0.28.jar直接添加到Java Build Path即可,

    然后我就可以毫无问题地连接到 JDBC。

    但是,如果我使用动态 Web 项目(在本例中),则适用这 2 条严格规则(jar 位置和类加载)。

    <参见TOMCAT ON ECLIPSE java.sql.SQLException:没有找到适合 jdbc:mysql 的驱动程序 >


Soln2(更新答案)//-20220305_12

简而言之:

  • 1 .将 mysql-connector-java-8.0.28.jar 文件放入 <安装 Tomcat 的位置>/lib 中。

    例如:G:\pla\Java\apache-tomcat-10.0.16\lib\mysql-connector-java-8.0.28.jar

    (对于 Eclipse 动态 Web 项目,该 jar 将自动放入项目的 Java 构建路径 > 服务器运行时 [Apache Tomcat v10.0].)

将 jar 放入 Tomcat/lib


附加说明: :

对于 soln1::

  1. mysql-connector-java-8.0.28.jar文件放入WEB-INF/lib中。
  2. 在 Servlet Java 代码中使用 Class.forName("com.mysql.cj.jdbc.Driver");

这将创建一个警告:

WARNING: The web application [LearnJDBC] appears to have started a thread named [mysql-cj-abandoned-connection-cleanup] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

Web 应用程序 [] 似乎启动了一个名为 [废弃连接清理线程] com.mysql.jdbc.AbandonedConnectionCleanupThread > 的线程

这个答案让我想到了 soln2。

对于 soln2::

  • <块引用>

    1. mysql-connector-java-8.0.28.jar文件放入<安装Tomcat的位置>/lib中。

    这将创建一个信息:

    信息:至少扫描了一个 JAR 的 TLD,但不包含 TLD。为此记录器启用调试日志记录,以获取已扫描但未在其中找到 TLD 的 JAR 的完整列表。在扫描期间跳过不需要的 JAR 可以缩短启动时间和 JSP 编译时间。
    
  • 你可以忽略它。

    <参见如何修复 Tomcat 9.0.0M10 中的“已扫描 JAR,但未在其中找到 TLD” >

  • (您现在应该了解 Murach 的 Java Servlet 和 JSP 正在讨论的内容:Tomcat/lib 中的 jar 以及不需要 Class.forName (“com.mysql.cj.jdbc.Driver”);)

  • 修复它//-20220307_23

    <块引用>
    汤姆猫8.5。在catalina.properties里面,位于/conf目录下设置:
    tomcat.util.scan.StandardJarScanFilter.jarsToSkip=\*.jar

    如何修复 JSP 编译器警告:扫描了一个 JAR 的 TLD 但不包含 TLD?

    “在

Summary:

  • Soln2 (recommend)::

    • 1 . put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.
  • Soln1::

    • 1 . put mysql-connector-java-8.0.28.jar file in the WEB-INF/lib.
    • 2 . use Class.forName("com.mysql.cj.jdbc.Driver"); in your Servlet Java code.

Soln1 (Ori Ans) //-20220304

In short:

  1. make sure you have the mysql-connector-java-8.0.28.jar file in the WEB-INF/lib
  2. make sure you use the Class.forName("com.mysql.cj.jdbc.Driver");

jar & class for jdbc connect


additional notes (not important), base on my trying (could be wrong)::

  • 1.1 putting the jar directly inside the Java build path doesnt work

  • 1.2. putting the jar in Data management > Driver Def > MySQL JDBC Driver > then add it as library to Java Build path doesnt work.

  • 1.3 => it has to be inside the WEB-INF/lib (I dont know why)

  • 1.4 using version mysql-connector-java-8.0.28.jar works, only version 5.1 available in Eclipse MySQL JDBC Driver setting doesnt matter, ignore it.

    <see How to connect to MySql 8.0 database using Eclipse Database Management Perspective >

  •     Class.forName("com.mysql.cj.jdbc.Driver");
        Class.forName("com.mysql.jdbc.Driver");
    

    both works,
    but the Class.forName("com.mysql.jdbc.Driver"); is deprecated.

    Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver class is generally unnecessary.
    

    <see https://www.yawintutor.com/no-suitable-driver-found-for-jdbcmysql-localhost3306-testdb/ >

  • If you want to connect to a MySQL database, you can use the type-4 driver named Connector/} that's available for free from the MySQL website. However, this driver is typically included in Tomcat's lib directory. As a result, you don't usually need to download this driver from the MySQL site.

    -- Murach’s Java Servlets and JSP

    I cant find the driver in Tomcat that the author is talking about, I need to use the mysql-connector-java-8.0.28.jar.
    <(striked-out) see updated answer soln2 below>

  • If you're working with an older version of Java, though, you need to use the forName method of the Class class to explicitly load the driver before you call the getConnection method

    Even with JDBC 4.0, you sometimes get a message that says, "No suitable driver found." In that case, you can use the forName method of the Class class to explicitly load the driver. However, if automatic driver loading works, it usually makes sense to remove this method call from your code.

    How to load a MySQL database driver prior to JDBC 4.0

    Class.forName{"com.mysql.jdbc.Driver");

    -- Murach’s Java Servlets and JSP

    I have to use Class.forName("com.mysql.cj.jdbc.Driver"); in my system, no automatic class loading. Not sure why.
    <(striked-out) see updated answer soln2 below>

  • When I am using a normal Java Project instead of a Dynamic Web Project in Eclipse,

    I only need to add the mysql-connector-java-8.0.28.jar to Java Build Path directly,

    then I can connect to the JDBC with no problem.

    However, if I am using Dynamic Web Project (which is in this case), those 2 strict rules applies (jar position & class loading).

    <see TOMCAT ON ECLIPSE java.sql.SQLException: No suitable driver found for jdbc:mysql >


Soln2 (Updated Ans) //-20220305_12

In short:

  • 1 . put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.

    eg: G:\pla\Java\apache-tomcat-10.0.16\lib\mysql-connector-java-8.0.28.jar

    (and for an Eclipse Dynamic Web Project, the jar will then be automatically put inside in your project's Java build path > Server Runtime [Apache Tomcat v10.0].)

put jar in Tomcat/lib


Additional notes::

for soln1::

  1. put mysql-connector-java-8.0.28.jar file in the WEB-INF/lib.
  2. use Class.forName("com.mysql.cj.jdbc.Driver"); in your Servlet Java code.

this will create an WARNING:

WARNING: The web application [LearnJDBC] appears to have started a thread named [mysql-cj-abandoned-connection-cleanup] but has failed to stop it. This is very likely to create a memory leak. Stack trace of thread:

<see The web application [] appears to have started a thread named [Abandoned connection cleanup thread] com.mysql.jdbc.AbandonedConnectionCleanupThread >

and that answer led me to soln2.

for soln2::

    1. put mysql-connector-java-8.0.28.jar file in the <where you install your Tomcat>/lib.

    this will create an INFO:

    INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
    
  • you can just ignore it.

    <see How to fix "JARs that were scanned but no TLDs were found in them " in Tomcat 9.0.0M10 >

  • (you should now understand what Murach’s Java Servlets and JSP was talking about: the jar in Tomcat/lib & the no need for Class.forName("com.mysql.cj.jdbc.Driver");)

  • to kinda fix it //-20220307_23

    Tomcat 8.5. Inside catalina.properties, located in the /conf directory set:
    tomcat.util.scan.StandardJarScanFilter.jarsToSkip=\*.jar

    How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

    skip scan in Tomcat/lib jar

梦幻的心爱 2024-08-21 09:07:50

使用指向驱动程序 JAR 文件的 CLASSPATH 环境变量运行 java,例如,

CLASSPATH='.:drivers/mssql-jdbc-6.2.1.jre8.jar' java ConnectURL

其中 drivers/mssql-jdbc-6.2.1.jre8.jar 是驱动程序文件的路径(例如 用于 SQL Server 的 JDBC)。

ConnectURL 是该驱动程序 (samples/connections/ConnectURL.java) 中的示例应用程序,通过 javac ConnectURL.java 编译。

Run java with CLASSPATH environmental variable pointing to driver's JAR file, e.g.

CLASSPATH='.:drivers/mssql-jdbc-6.2.1.jre8.jar' java ConnectURL

Where drivers/mssql-jdbc-6.2.1.jre8.jar is the path to driver file (e.g. JDBC for for SQL Server).

The ConnectURL is the sample app from that driver (samples/connections/ConnectURL.java), compiled via javac ConnectURL.java.

流云如水 2024-08-21 09:07:50

无论这条线索有多老,人们都会继续面对这个问题。

我的案例:我有最新的(在发布时)OpenJDK 和 maven 设置。我已经尝试了上面给出的所有方法,有/没有 Maven,甚至 StackOverflow 上姐妹帖子上的解决方案。我没有使用任何 IDE 或其他任何东西,只是从裸 CLI 运行来演示核心逻辑。

这就是最终奏效的。

  • 从官方网站下载驱动程序。 (对我来说,这是 MySQL https://www.mysql.com/products/connector/)。在这里发挥你的味道。
  • 将给定的 jar 文件解压到与 java 项目相同的目录中。你会得到这样的目录结构。如果您仔细观察,这与我们尝试使用 Class.forName(....) 执行的操作完全相关。我们想要的文件是 com/mysql/jdbc/Driver.class

https://i .sstatic.net/KG1jY.png

  • 编译包含代码的java程序。
javac App.java
  • 现在通过运行将director加载为模块,
java --module-path com/mysql/jdbc -cp ./ App

这将手动加载(提取的)包,并且您的java程序将找到所需的Driver类。


  • 请注意,这是针对 mysql 驱动程序完成的,其他驱动程序可能需要进行较小的更改。
  • 如果您的供应商提供了 .deb 映像,您可以从 /usr/share/java/your-vendor-file-here.jar 获取 jar

No matter how old this thread becomes, people would continue to face this issue.

My Case: I have the latest (at the time of posting) OpenJDK and maven setup. I had tried all methods given above, with/out maven and even solutions on sister posts on StackOverflow. I am not using any IDE or anything else, running from bare CLI to demonstrate only the core logic.

Here's what finally worked.

  • Download the driver from the official site. (for me it was MySQL https://www.mysql.com/products/connector/). Use your flavour here.
  • Unzip the given jar file in the same directory as your java project. You would get a directory structure like this. If you look carefully, this exactly relates to what we try to do using Class.forName(....). The file that we want is the com/mysql/jdbc/Driver.class

https://i.sstatic.net/KG1jY.png

  • Compile the java program containing the code.
javac App.java
  • Now load the director as a module by running
java --module-path com/mysql/jdbc -cp ./ App

This would load the (extracted) package manually, and your java program would find the required Driver class.


  • Note that this was done for the mysql driver, other drivers might require minor changes.
  • If your vendor provides a .deb image, you can get the jar from /usr/share/java/your-vendor-file-here.jar
べ映画 2024-08-21 09:07:50

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

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

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 File Properties Dialog:
Windows JAR File Properties Dialog

独自唱情﹋歌 2024-08-21 09:07:50

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

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.

伪心 2024-08-21 09:07:50

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

我的意思是:-

假设你有错误给定 jdbc url

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

(注意 url 的开头有一个空格,这将导致错误)

正确的方法应该是:(

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

注意开头没有空格,你可以在网址末尾留出空格,但不这样做是安全的)

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

What I mean is:-

suppose u have bymistake given the jdbc url like

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)

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)

不羁少年 2024-08-21 09:07:50

我使用的是 jruby,在我的例子中,我在 config/initializers

postgres_driver.rb

$CLASSPATH << '~/.rbenv/versions/jruby-1.7.17/lib/ruby/gems/shared/gems/jdbc-postgres-9.4.1200/lib/postgresql-9.4-1200.jdbc4.jar'

或您的驱动程序所在的任何位置创建,就是这样!

I was using jruby, in my case I created under config/initializers

postgres_driver.rb

$CLASSPATH << '~/.rbenv/versions/jruby-1.7.17/lib/ruby/gems/shared/gems/jdbc-postgres-9.4.1200/lib/postgresql-9.4-1200.jdbc4.jar'

or wherever your driver is, and that's it !

待天淡蓝洁白时 2024-08-21 09:07:50

我在 STS 中开发 Spring Boot 应用程序时遇到了这个问题,但最终将打包的 war 部署到 WebSphere(v.9)。根据之前的答案,我的情况很独特。 ojdbc8.jar 位于我的 WEB-INF/lib 文件夹中,并设置了 Parent Last 类加载集,但总是显示无法找到合适的驱动程序。

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

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

使用 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;
    }
}

以及使用 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;
    }
}

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.

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]

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

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

@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:

@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;
    }
}
染墨丶若流云 2024-08-21 09:07:50

我在使用 spring data 的 mysql 数据源上遇到了同样的问题,它可以在外面工作,但在部署到 tomcat 上时却出现了这个错误。

当我将驱动程序 jar mysql-connector-java-8.0.16.jar 添加到 jres lib/ext 文件夹时,错误消失了。

但是,我不想在生产中执行此操作,因为担心干扰其他应用程序。显式定义驱动程序类为我解决了这个问题

    spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver

I was having the same issue with mysql datasource using spring data that would work outside but gave me this error when deployed on tomcat.

The error went away when I added the driver jar mysql-connector-java-8.0.16.jar to the jres lib/ext folder

However I did not want to do this in production for fear of interfering with other applications. Explicity defining the driver class solved this issue for me

    spring.datasource.driver-class-name: com.mysql.cj.jdbc.Driver
不美如何 2024-08-21 09:07:50

如果没有为您的应用程序提供资源定义,您将得到同样的错误——很可能是在中央 context.xml 中,或者在 conf/Catalina/localhost 中的单独上下文文件中。如果使用单独的上下文文件,请注意,只要您删除/取消部署相应的 .war 文件,Tomcat 就会随意删除它们。

You will get this same error if there is not a Resource definition provided somewhere for your app -- most likely either in the central context.xml, or individual context file in conf/Catalina/localhost. And if using individual context files, beware that Tomcat freely deletes them anytime you remove/undeploy the corresponding .war file.

旧人哭 2024-08-21 09:07:50

对我来说,在从表创建数据帧时连接到 postgres 时发生了同样的错误。这是由于缺少依赖项引起的。未设置 jdbc 依赖项。我使用 maven 进行构建,因此将所需的依赖项添加到 maven 依赖

jdbc 依赖

For me the same error occurred while connecting to postgres while creating a dataframe from table .It was caused due to,the missing dependency. jdbc dependency was not set .I was using maven for the build ,so added the required dependency to the pom file from maven dependency

jdbc dependency

夏见 2024-08-21 09:07:50

对我来说,将以下依赖项添加到 pom.xml 文件就像魔术一样解决了!我没有 mysql 连接器依赖性,甚至将 mssql jdbc jar 文件添加到构建路径也不起作用。

    <dependency> 
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <version>9.4.0.jre11</version>
    </dependency>

For me adding below dependency to pom.xml file just solved like magic! I had no mysql connector dependency and even adding mssql jdbc jar file to build path did not work either.

    <dependency> 
        <groupId>com.microsoft.sqlserver</groupId>
        <artifactId>mssql-jdbc</artifactId>
        <version>9.4.0.jre11</version>
    </dependency>
不可一世的女人 2024-08-21 09:07:50

就我而言,我正在使用 Maven 处理 Java 项目并遇到此错误。
在您的 pom.xml 文件中,确保您具有此依赖项

<dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>
  </dependencies>

,并且创建连接的位置具有类似的内容

public Connection createConnection() {
        try {
            String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
            String username = "root"; //your my sql username here
            String password = "1234"; //your mysql password here

            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }

In my case I was working on a Java project with Maven and encountered this error.
In your pom.xml file make sure you have this dependencies

<dependencies>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>8.0.11</version>
    </dependency>
  </dependencies>

and where you create connection have something like this

public Connection createConnection() {
        try {
            String url = "jdbc:mysql://localhost:3306/yourDatabaseName";
            String username = "root"; //your my sql username here
            String password = "1234"; //your mysql password here

            Class.forName("com.mysql.cj.jdbc.Driver");
            return DriverManager.getConnection(url, username, password);
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }

        return null;
    }
橪书 2024-08-21 09:07:50

面临同样的问题。在我的例子中,'//'(jdbc:mysql://localhost:3306/dbname)之前的':'冒号丢失了,它只是解决了问题。
确保 : 和 // 放置正确。

faced same issue. in my case ':' colon before '//' (jdbc:mysql://localhost:3306/dbname) was missing, and it just fixed the problem.
make sure : and // are placed properly.

攒眉千度 2024-08-21 09:07:50

我遇到了同样的错误。就我而言,JDBC URL 是正确的,但问题出在 classpath 上。但是,将 MySQL 连接器的 JAR 文件添加到 -classpath-cp(或者,如果是 IDE,则作为库)并不能解决问题。因此,我必须将 JAR 文件移动到 Java 字节码的位置并运行 java -cp :mysql_connector.jar 才能完成这项工作。如果有人遇到与我相同的问题,我会将其留在这里。

I ran into the same error. In my case, the JDBC URL was correct, but the issue was with classpath. However, adding MySQL connector's JAR file to the -classpath or -cp (or, in the case of an IDE, as a library) doesn't resolve the issue. So I will have to move the JAR file to the location of Java bytecode and run java -cp :mysql_connector.jar to make this work. If someone runs into the same issue as mine, I'm leaving this here.

宛菡 2024-08-21 09:07:50

我遇到了同样的异常,但在 H2 数据库上,它出现是因为我在 doFilter 中进行了初始请求对象操作。我这样做是因为我需要多次读取请求的正文,但由于某种原因,它中断了与 H2 控制台的连接。这就是我所做的,为我解决了这个问题:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (((HttpServletRequest) request).getRequestURI().startsWith("/h2-console/")) {
        chain.doFilter(request, response);
        return;
    }
    RepeatableHttpServletRequestWrapper wrappedRequest = new RepeatableHttpServletRequestWrapper((HttpServletRequest) request);
    chain.doFilter(wrappedRequest, response);
}

I faced the same exception but on the H2 database and it appeared because of my initial request object manipulation in doFilter. I did it cuz I needed to read the Body of the request multiple times, but for some reason, it broke the connection to the H2 console. So this is what I did, that fixed this issue for me:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (((HttpServletRequest) request).getRequestURI().startsWith("/h2-console/")) {
        chain.doFilter(request, response);
        return;
    }
    RepeatableHttpServletRequestWrapper wrappedRequest = new RepeatableHttpServletRequestWrapper((HttpServletRequest) request);
    chain.doFilter(wrappedRequest, response);
}
2024-08-21 09:07:50

如果你使用Maven并将你的项目打包成war,你应该注意jar是否成功下载到你的Maven repo中,经过检查以上方法我终于发现我的Mysql 8.0.33版本是下载失败,如下:
除了jar文件外,其他所有文件如repositories、sha1和pom都下载成功

因此,如果您是 Maven 用户,请不要忘记检查您的存储库

If you're using Maven and packaging your project into war, you should notice whether the jar is successfully downloaded in your Maven repo, after checking all above methods I finally found my 8.0.33 version of Mysql is downloaded failed like this:
except for jar file, all other files like repositories, sha1 and pom are downloaded successfully.

So if you are Maven user, don't forget to check your repo!

So尛奶瓶 2024-08-21 09:07:50

我遇到这个问题是因为错误地将 XML 文件放入 src/main/resources 中,我将其删除,然后一切恢复正常。

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文