JAVA/JSP & Servlet

JDBC 연결 - 오류 발생의 사례들

gakko 2022. 1. 19. 13:40

JDBC를 사용하다보면 여러가지 오류가 발생하게 되는데

대체로 url이나 driver 설정과정에서 문제가 생긴다

 

1. driver 문제

문제의 코드

Class.forName("com.mysql.jdbc.Driver");
  • 예전에 쓰이던 드라이버 클래스이다.
  • 실행은 되지만 아래와 같은 경고창이 뜬다.
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.

 

 

 

정상작동한 코드

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

라고 꼭 적어주자!!

 

 

 

2. URL 문제 - Timezone Error

문제의 코드

String url = "jdbc:mysql://localhost:3306/mydb";

 

위와 같이 코드를 적으면

The server time zone value '´???¹?±¹ ???ؽ?' is unrecognized or represents more than one time zone.

와 같이 time zone 에러가 발생하게 된다.

jdbc:mysql://localhost:3306/mydb 뒤에 ?serverTimezone=UTC를 붙여주면된다....

그런데 여기서 또 에러가 발생한다.

 

 

 

3. URL 문제 - SSLException 에러

문제의 코드

String url = "jdbc:mysql://localhost:3306/musthave?serverTimezone=UTC";

이번엔

javax.net.ssl.SSLException: closing inbound before receiving peer's close_notify

오류가 발생하기 시작한다.

SSL은 전송 계층 보안(TRansport Layer Security, TLS)으로 컴퓨터 네트워크에 통신 보안을 제공하기 위해

설계된 암호 규약인데 이것이 의도치 않게 DB연결을 방해한다.

 

정상적인 코드

String url = "jdbc:mysql://localhost:3306/musthave?useSSL=false&serverTimezone=UTC";
  • 정상작동하는 코드이다.
  • SSL 설정을 해체하는 것이기 때문에 보안상 굉장히 안 좋을 수 있다. (DB에 개인 정보가 있다면 절대 NO!!!!!!!)
String url = "jdbc:mysql://localhost:3306/musthave?useSSL=false&characterEncoding=UTF-8
			&serverTimezone=UTC";
  • 사실상 그렇게 필요하진 않지만 확실히 하고 싶다면 UTF-8을 설정해놓는 것도 좋다.

 

 

 

 

정상적인 코드 종합

package common;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;


public class JDBConnect {
	public Connection con;
	public Statement stmt;
	public PreparedStatement psmt;
	public ResultSet rs;
	
	public JDBConnect() {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
			
			String url = "jdbc:mysql://localhost:3306/musthave?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTC";
			String user = "mysql_user";   // 대체로 root
			String pwd = "mysql_pwd";     // 설치할 때 설정했던 비밀번호
			con = DriverManager.getConnection(url, user, pwd);
			
			System.out.println("DB Connection Success");
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
		try {
			if (rs != null) rs.close();
			if(stmt != null) stmt.close();
			if(psmt != null) psmt.close();
			if(con != null) con.close();
			
			System.out.println("JDBC Disconnection!");
			
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}