MySQL DB 연결 : (JSP, MySQL, MariaDB)
1. JDBC 드라이버 설치
JAR 파일을 다운로드해서 WEB-INF/lib 폴더에 추가
MySQL : MySQL Connector/J
MariaDB : MariaDB Connector/J (MariaDB 사용시에 설치)
2. DB 정보 설정 파일 작성 (db.properties)
파일 위치 : WEB-INF/db.properties
db.url=jdbc:mysql://localhost:3306/mydb
db.user=dbuser
db.password=1234
db.driver=com.mysql.cj.jdbc.Driver
MariaDB 사용 시 변경 :
db.url=jdbc:mariadb://localhost:3306/mydb
db.driver=org.mariadb.jdbc.Driver
3. JSP DB 연결 (db.jsp)
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.Properties" %>
<%@ page import="java.io.InputStream" %>
<%
Properties db = new Properties();
try (InputStream in = application.getResourceAsStream("/WEB-INF/db.properties")) {
if (in == null) {
throw new Exception("DB 설정 파일 없음");
}
db.load(in);
Class.forName(db.getProperty("db.driver"));
try (Connection conn = DriverManager.getConnection(
db.getProperty("db.url"),
db.getProperty("db.user"),
db.getProperty("db.password"))) {
out.println("DB 연결 성공");
}
} catch (Exception e) {
out.println("DB 연결 실패");
application.log("DB 연결 오류", e);
}
%>
4. 실행 결과 예시
브라우저에서 db.jsp에 접속.
연결 성공 : DB 연결 성공
연결 실패 : DB 연결 실패
5. DB 접속 정보 변경
DB 주소, 데이터베이스 이름, 사용자명, 비밀번호가 변경되면 db.properties 파일만 수정.
(※ 운영시에는 별도 DB 계정을 사용, db.properties 파일은 비공개 저장소에)