Ⅷ. 게시물 수정기능 구현
1. 게시물 수정기능 구현
- 게시물을 수정하기 위해서는 Main.java에 다음과 같이 입력함
package exam;
import java.sql.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("==프로그램 시작==");
int lastArticleId = 0;
while (true) {
System.out.printf("명령어 ) ");
String cmd = sc.nextLine().trim();
if (cmd.equals("exit")) {
System.out.println("===종료===");
break;
}
if (cmd.equals("article write")) {
System.out.println("== 게시물 작성 ==");
int id = lastArticleId + 1;
System.out.printf("제목 : ");
String title = sc.nextLine();
System.out.printf("내용 : ");
String body = sc.nextLine();
System.out.printf("%d번글이 생성되었습니다\n", id);
Article article = new Article(id, title, body);
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/JDBCTest?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul&useOldAliasMetadataBehavior=true&zeroDateTimeNehavior=convertToNull";
conn = DriverManager.getConnection(url, "root", "");
System.out.println("연결 성공!");
String sql = "INSERT INTO article";
sql += " SET regDate = NOW()";
sql += ", updateDate = NOW()";
sql += ", title = '" + title + "'";
sql += ", `body` = '" + body + "';";
System.out.println(sql);
pstmt = conn.prepareStatement(sql);
int affectedRows = pstmt.executeUpdate();
System.out.println(affectedRows + "열에 적용됨");
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
} catch (SQLException e) {
System.out.println("에러: " + e);
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null && !pstmt.isClosed()) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
lastArticleId++;
} else if (cmd.startsWith("article modify ")) {
int id = Integer.parseInt(cmd.split(" ")[2]);
System.out.printf("== %d번 게시물 수정 ==", id);
System.out.printf("새 제목 : ");
String title = sc.nextLine();
System.out.printf("새 내용 : ");
String body = sc.nextLine();
Connection conn = null;
PreparedStatement pstmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/JDBCTest?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul&useOldAliasMetadataBehavior=true&zeroDateTimeNehavior=convertToNull";
conn = DriverManager.getConnection(url, "root", "");
System.out.println("연결 성공!");
String sql = "UPDATE article";
sql += " SET updateDate = NOW()";
sql += ", title = '" + title + "'";
sql += ", `body` = '" + body + "'";
sql += " WHERE id = " + id + ";";
System.out.println(sql);
pstmt = conn.prepareStatement(sql);
int affectedRows = pstmt.executeUpdate();
System.out.println(affectedRows + "열에 적용됨");
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
} catch (SQLException e) {
System.out.println("에러: " + e);
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null && !pstmt.isClosed()) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.printf("%d번 게시물이 수정 되었습니다.", id);
} else if (cmd.equals("article list")) {
System.out.println("== 게시물 리스트 ==");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
List<Article> articles = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://127.0.0.1:3306/JDBCTest?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul&useOldAliasMetadataBehavior=true&zeroDateTimeNehavior=convertToNull";
conn = DriverManager.getConnection(url, "root", "");
System.out.println("연결 성공!");
String sql = "SELECT *";
sql += " FROM article";
sql += " ORDER BY id DESC";
System.out.println(sql);
pstmt = conn.prepareStatement(sql);
rs = pstmt.executeQuery();
while (rs.next()) {
int id = rs.getInt("id");
String regDate = rs.getString("regDate");
String updateDate = rs.getString("updateDate");
String title = rs.getString("title");
String body = rs.getString("body");
Article article = new Article(id, regDate, updateDate, title, body);
articles.add(article);
}
} catch (ClassNotFoundException e) {
System.out.println("드라이버 로딩 실패");
} catch (SQLException e) {
System.out.println("에러: " + e);
} finally {
try {
if (rs != null && !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (pstmt != null && !pstmt.isClosed()) {
pstmt.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
if (articles.size() == 0) {
System.out.println("게시물이 없습니다");
continue;
}
System.out.println("번호 | 제목");
for (int i = 0; i < articles.size(); i++) {
Article article = articles.get(i);
System.out.printf("%4d | %s\n", article.id, article.title);
}
}
}
}
}
2. 실행
- 명령어에 article list를 입력
- 명령어에 article modify 2를 입력
- 테이블의 2번 행을 수정할 수 있음
- 확인
'Back-End Study > DBMS' 카테고리의 다른 글
JDBC - 10. DBUtil과 SecSql을 이용하여 Main의 방식 수정 (0) | 2022.09.07 |
---|---|
JDBC - 9. article DELETE 기능 구현 (0) | 2022.09.07 |
JDBC - 7. article list 시, 데이터를 DB로부터 가져오기 (0) | 2022.09.06 |
JDBC - 6. JDBC SELECT 테스트 (0) | 2022.09.06 |
JDBC - 5. 게시물 작성 시, DB에 INSERT (0) | 2022.09.05 |