✍️ 관련 강의: DB - DBC 게시판 실습2 (DBUtil.java)
드라이버 로딩, Connection 생성, 해제 등을 하나의 클래스에서 관리한다.
package com.ssafy.board.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtil {
// MySql 드라이버 클래스 이름
private final String driverName = "com.mysql.cj.jdbc.Driver";
// DB와 연결하기 위해 필요한 URL
private final String url = "jdbc:mysql://localhost:3306/ssafy_board?serverTimezone=UTC";
// USER 정보
private final String username = "ssafy";
private final String password = "ssafy";
private static DBUtil instance = new DBUtil();
private DBUtil() {
// JDBC 드라이버를 로딩
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static DBUtil getInstance() {
return instance;
}
/**
* DriverManager를 통해 나의 username와 password를 이용하여 Connection을 반환
* Connection은 인터페이스므로 new 객체생성연산자로 만들어낼 수 없다.
* @return Connection
* @throws SQLException
*/
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
/**
* 사용한 리소스들을 정리한다. Connection, Statement, PreparedStatement, ResultSet 모두
* AutoCloseable 타입 ...(가변인자)를 이용하므로 필요에 한번에 정리가능
*
* @param autoCloseables
*/
public void close(AutoCloseable...autoCloseables ) {
for(AutoCloseable ac : autoCloseables) {
if(ac != null) {
try {
ac.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}