악명 높은 java.sql.SQLException : 적합한 드라이버가 없습니다.
기존 Tomcat 5.5 응용 프로그램 (도움이되는 경우 GeoServer 2.0.0)에 데이터베이스 사용 JSP를 추가하려고합니다.
앱 자체는 Postgres와 잘 대화하므로 데이터베이스가 작동하고 사용자가 액세스 할 수 있다는 것을 알고 있습니다. 내가하려는 것은 내가 추가 한 JSP의 데이터베이스 쿼리입니다. 나는 Tomcat 데이터 소스 예제 의 구성 예제 를 거의 즉시 사용했습니다. 필수 taglib가 올바른 위치에 있습니다. taglib 참조 만 있으면 오류가 발생하지 않으므로 해당 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의 관련 섹션은 <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>
다음 행은 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]
악명 높은 java.sql.SQLException : 적합한 드라이버가 없습니다.
이 예외는 기본적으로 두 가지 원인 이있을 수 있습니다 .
1. JDBC 드라이버가로드되지 않았습니다.
JDBC 드라이버가 서버의 자체 /lib
폴더 에 있는지 확인해야 합니다.
또는 실제로 서버 관리 연결 풀 데이터 소스를 사용하지 않고 DriverManager#getConnection()
WAR에서 수동으로 조작 하는 경우 JDBC 드라이버를 WAR에 배치하고 /WEB-INF/lib
..
Class.forName("com.example.jdbc.Driver");
.. 첫 번째 호출 전에 코드에서 던질 수있는 것을 삼키거나 무시 DriverManager#getConnection()
하지 않도록ClassNotFoundException
하고 예외가없는 것처럼 코드 흐름을 계속합니다. Tomcat의 연결 풀에 대한 JDBC 드라이버를 어디에 배치해야합니까?를 참조하십시오 .
2. 또는 JDBC URL의 구문이 잘못되었습니다.
JDBC URL이 JDBC 드라이버 문서를 준수하는지 확인하고 일반적으로 대소 문자를 구분한다는 점에 유의해야합니다. 로드 된 드라이버 true
에 Driver#acceptsURL()
대해 JDBC URL이 반환되지 않으면 정확히이 예외가 발생합니다.
PostgreSQL의 경우 여기 에 설명되어 있습니다 .
JDBC에서 데이터베이스는 URL (Uniform Resource Locator)로 표시됩니다. PostgreSQL ™에서는 다음 형식 중 하나를 사용합니다.
jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
MySQL 서버에 연결하기위한 JDBC URL의 일반적인 형식은 다음과 같으며 대괄호 (
[ ]
) 안의 항목 은 선택 사항입니다.
jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]] » [?propertyName1=propertyValue1[&propertyName2=propertyValue2]...]
2 개의 URL 구문, SID에서만 작동하는 이전 구문과 Oracle 서비스 이름에서 새로운 구문이 있습니다.
이전 구문
jdbc:oracle:thin:@[HOST][:PORT]:SID
새로운 구문
jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE
또한보십시오:
- Tomcat의 연결 풀에 대한 JDBC 드라이버를 어디에 배치해야합니까?
- java.lang.ClassNotFoundexception을 사용하지 않고 Eclipse 웹 프로젝트에 JDBC 드라이버를 설치하는 방법
- 서블릿 기반 애플리케이션에서 JDBC 데이터베이스 / 데이터 소스에 어떻게 연결해야합니까?
- "Class.forName ()"과 "Class.forName (). newInstance ()"의 차이점은 무엇입니까?
- MySQL 데이터베이스에 Java 연결
url="jdbc:postgresql//localhost:5432/mmas"
URL이 잘못된 것 같습니다. 다음이 필요합니까?
url="jdbc:postgresql://localhost:5432/mmas"
비슷한 문제에 직면했습니다. 내 프로젝트는 Dynamic Web Project (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());
}
PostgreSQL JDBC 드라이버를 Mvnrepository 프로젝트에 추가하는 것을 잊었습니다 .
Gradle :
// http://mvnrepository.com/artifact/postgresql/postgresql
compile group: 'postgresql', name: 'postgresql', version: '9.0-801.jdbc4'
메이븐 :
<dependency>
<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
</dependency>
JAR을 다운로드 하고 수동으로 프로젝트로 가져올 수도 있습니다.
Tomcat에서이 문제를 제거하는 데 도움이되는 다음 팁을 찾았습니다.
먼저 Class.forName ( "org.postgresql.Driver");을 수행하여 드라이버를로드해야합니다. 귀하의 코드에서.
이것은 게시물에서 가져온 것입니다-https: //www.postgresql.org/message-id/e13c14ec050510103846db6b0e@mail.gmail.com
jdbc 코드는 독립 실행 형 프로그램으로 잘 작동했지만 TOMCAT에서는 '적합한 드라이버를 찾을 수 없음'오류가 발생했습니다.
Windows가 안전하지 않은 것으로 간주되는 다운로드를 차단할 때도 발생할 수 있습니다. jar 파일 (예 : ojdbc7.jar)을 마우스 오른쪽 버튼으로 클릭하고 하단의 '차단 해제'상자를 선택하면이 문제를 해결할 수 있습니다.
Windows JAR 파일 속성 대화 상자 :
나는 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'
또는 운전자가 어디에 있든 그게 전부입니다!
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.
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;
}
}
I encountered this issue by putting a XML file into the src/main/resources
wrongly, I deleted it and then all back to normal.
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)
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
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
.
'IT박스' 카테고리의 다른 글
Alamofire를 사용한 NSURLSession 동시 요청 (0) | 2020.11.08 |
---|---|
Asp.net-mvc 컨트롤러 컨텍스트 모의 (0) | 2020.11.08 |
페이지 콘텐츠 위에 div 플로팅 (0) | 2020.11.08 |
$ (문서) .ready (function () VS $ (function () { (0) | 2020.11.08 |
return 문에서 결과 주위의 괄호가 의미가 있습니까? (0) | 2020.11.08 |