JDBC(Java Database Connectivity)는 데이터를 저장하고 읽어오거나, 업데이트 및 삭제와 같은 작업을 수행할 수 있도록 지원하는 Java API입니다. 이 글에서는 JDBC의 주요 절차와 MySQL 데이터베이스와의 연결 방법을 알아보겠습니다!
JDBC 작업은 예외가 발생할 수 있으므로 모든 작업은 try-catch 블록 내에서 처리해야 합니다. 아래는 JDBC의 기본 절차입니다.
.jar
파일을 메모리에 로드합니다.PreperedStatement
객체에 담습니다.executeQuery()
: SELECT 문 실행 (결과 반환)executeUpdate()
: DML(insert, update, delete) 실행 (성공 여부 반환)ResultSet
객체를 사용하여 데이터를 처리합니다.Connection
, PreparedStatement
, ResultSet
)를 닫아줍니다.public class DatabaseApp {
public static final String URL = "jdbc:mysql://localhost:3306/DB_NAME?serverTimezone=UTC";
public static final String DRIVER = "com.mysql.cj.jdbc.Driver";
public static final String USER = "USER";
public static final String PASSWORD = "PASSWORD";
public static Connection conn;
}
public static void init() {
try {
Class.forName(DRIVER); // 드라이버 로드
System.out.println("Driver Loading OK!!");
conn = DriverManager.getConnection(URL, USER, PASSWORD); // 커넥션 생성
System.out.println("DB Server Connection OK!!" + conn);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
init();
}
tb_post
테이블은 다음과 같이 구성됩니다.
Column Name | Type | Description |
---|---|---|
id | INT | Primary Key |
title | VARCHAR(255) | 게시물 제목 |
content | VARCHAR(255) | 게시물 내용 |
writer | VARCHAR(100) | 작성자 |
created_date | TIMESTAMP | 생성일 |
public static void insertRow() {
PreparedStatement pstmt = null;
String insertSQL = "INSERT INTO tb_post(title, content, writer) VALUES(?,?,?)";
int flag = 0;
try {
pstmt = conn.prepareStatement(insertSQL);
pstmt.setString(1, "즐거운 하루");
pstmt.setString(2, "JDBC를 배워봅시다");
pstmt.setString(3, "심썽");
flag = pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("DML Result >>> " + flag);
}
}
public static void main(String[] args) {
init();
System.out.println(">>> 데이터 삽입 시작");
insertRow();
}
테이블의 모든 데이터를 조회합니다.
public static List<PostResponseDTO> selectAllRows() {
List<PostResponseDTO> list = new ArrayList<>();
PreparedStatement pstmt = null;
ResultSet rset = null;
String selectSQL = "SELECT id, title, content, writer, created_date FROM tb_post";
try {
pstmt = conn.prepareStatement(selectSQL);
rset = pstmt.executeQuery();
while (rset.next()) {
PostResponseDTO response = new PostResponseDTO();
response.setId(rset.getInt("id"));
response.setTitle(rset.getString("title"));
response.setContent(rset.getString("content"));
response.setWriter(rset.getString("writer"));
response.setCreatedDate(rset.getTimestamp("created_date"));
list.add(response);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rset != null) rset.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return list;
}
public static void main(String[] args) {
init();
System.out.println(">>> 데이터 조회 시작");
List<PostResponseDTO> list = selectAllRows();
list.forEach(System.out::println);
}
특정 조건(ID 값)을 사용해 데이터를 조회합니다.
public static PostResponseDTO selectById(int id) {
PreparedStatement pstmt = null;
ResultSet rset = null;
String selectSQL = "SELECT id, title, content, writer, created_date FROM tb_post WHERE id = ?";
PostResponseDTO response = null;
try {
pstmt = conn.prepareStatement(selectSQL);
pstmt.setInt(1, id);
rset = pstmt.executeQuery();
if (rset.next()) {
response = new PostResponseDTO();
response.setId(rset.getInt("id"));
response.setTitle(rset.getString("title"));
response.setContent(rset.getString("content"));
response.setWriter(rset.getString("writer"));
response.setCreatedDate(rset.getTimestamp("created_date"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (rset != null) rset.close();
if (pstmt != null) pstmt.close();
if (conn != null) conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
public static void main(String[] args) {
init();
System.out.println(">>> ID로 데이터 조회");
PostResponseDTO response = selectById(1);
System.out.println(response);
}