2024-01-08 (21일차) - JDBC 게시판

민짱·2024년 1월 8일

📅2024. 01. 08 21일차


🎬JDBC_AM 시작

🔐 문제 해결

  • article list 시 SELECT 된 결과가 콘솔에 보일 수 있도록 구현

💡띵킹

  • SelectTest 확인 결과 이상 없이 실행
  • ==>Main class에서 실행되도록 article list 입력 시 console에 보일 수 있도록 구현되어야 한다?
  • 그럼 SelectTest에 있는 걸 일단 복사해서 넣어볼까??
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/JDBC_AM?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(sql);

					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);

					}
//					for (int i = 0; i < articles.size(); i++) {
//						System.out.println("번호 : " + articles.get(i).getId());
//						System.out.println("등록 날짜 : " + articles.get(i).getRegDate());
//						System.out.println("수정 날짜 : " + articles.get(i).getUpdateDate());
//						System.out.println("제목 : " + articles.get(i).getTitle());
//						System.out.println("내용 : " + articles.get(i).getBody());
//					}

				} 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 (Article article : articles) {
					System.out.printf("  %d     /   %s   \n", article.getId(), article.getTitle());
				}
			}

		}

🔑해결완료.

🔓 게시물 수정 기능 구현 ==> JDBC 활용

💡띵킹

  • ==> JDBC활용? JDBC에 저장 되 있는 게시물을 수정한다.
UPDATE article
SET title = 123
WHERE id = 1

UPDATE article
SET `body` = 123
WHERE id = 1
  • 이 방법으로 수정 가능? 그럼 SELECT을 가져와서 sql 문만 바꿔주면 되나?

  • try = 수정은 된다. but 현재 문제점 ?= 지정된 번호만 바뀜...

  • 어떻게 하면 입력 받은 번호를 수정하게 만들까?

🔑 문제 해결

  • 입력 값을 받아와 Update 한다. 원하는 번호와 제목, 내용 수정 가능 문제 해결.

					System.out.println("수정할 게시글번호 : ");
					int num = sc.nextInt();
					System.out.println("수정할 제목 : ");
					String title = sc.next();
					System.out.println("수정할 내용 : ");
					String body = sc.next();
					
					
					
					String sql = "UPDATE article";
					sql += " SET title = '" + title + "', `body` = '" + body;
					sql += " WHERE id = " + num;

🔐문제 발생

  • 연결 성공도 되고 입력도 되는데 입력해도 수정이 되지 않는다... why... 머가 문제지...
	sql += " SET title = '" + title + "', `body` = '" + body;
  • sql 명령문 body에 body로 들어가서 명령어로 인지 못 했었다.. 바본가...

🔑 수정 (해결완료)

" SET title = '" + title + "', body = '" + body

🏆슨생님 ver.

else if (cmd.startsWith("article modify")) {

				int id = 0;

				try {
					id = Integer.parseInt(cmd.split(" ")[2]);
				} catch (Exception e) {
					System.out.println("번호는 정수로 입력해");
					continue;
				}

				System.out.println("==수정==");
				System.out.print("새 제목 : ");
				String title = sc.nextLine().trim();
				System.out.println("새 내용 : ");
				String body = sc.nextLine().trim();
String sql = "UPDATE article";
					sql += " SET updateDate = NOW()";
					if (title.length() > 0) {
						sql += " ,title = '" + title + "'";
					}
					if (body.length() > 0) {
						sql += " ,`body` = '" + body + "'";
					}
					sql += " WHERE id = " + id + ";";

					System.out.println(sql);

					pstmt = conn.prepareStatement(sql);

					pstmt.executeUpdate();
  • 슨생님 ver.에는 split() 사용하여 문자열 쪼개기
if (title.length() > 0) {} //  나는 내용만 저장하고 싶어! 안 쓰면 그대로~
if (body.length() > 0) {} //  나는 제목만 저장하고 싶어! 안 쓰면 그대로~

리펙토링

🔓 게시물 삭제 기능 구현 ==> JDBC 활용

💡띵킹

  • ==> JDBC활용? JDBC에 저장 되 있는 게시물을 삭제한다.
  • 그럼 수정이랑 비슷한거 아닌가? 수정을 가져와서 좀만 고치면 될 듯???

🔑 문제 해결

  • sql문을 활용 이제 원하는 번호 삭제 가능!! 문제는 입력받은 id값을 삭제해야함..?
  • sql문을 이용해서 java에서 구현되게 하자
DELETE FROM article WHERE id = 1
  • 이대로 java에서 구현

🔑 문제 해결

System.out.println("==글 삭제==");
				System.out.println("삭제할 게시글번호 : ");
				int num = sc.nextInt();

				System.out.printf("%d 번 글이 삭제되었습니다.\n", num);

				Connection conn = null;
				PreparedStatement pstmt = null;

				try {
					Class.forName("com.mysql.jdbc.Driver");
					String url = "jdbc:mysql://127.0.0.1:3306/JDBC_AM?useUnicode=true&characterEncoding=utf8&autoReconnect=true&serverTimezone=Asia/Seoul&useOldAliasMetadataBehavior=true&zeroDateTimeNehavior=convertToNull";

					conn = DriverManager.getConnection(url, "root", "");
					System.out.println("연결 성공!");

					String sql = " DELETE FROM article "
							   + " WHERE id = '" + num + "'";
					
					System.out.println(sql);

					pstmt = conn.prepareStatement(sql);

					int affectedRow = pstmt.executeUpdate();

					System.out.println("affectedRow : " + affectedRow);

				} 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();
					}
				}

🔓 게시물 상세보기 기능 구현 ==> JDBC 활용

💡띵킹

  • list 내용과 비슷한 것 같다. 일단 가져와 보자
  • 수정할 내용은 list처럼 다 나오는게 아닌 내가 원하는 게시글만 보이도록 구현!!!
SELECT *
FROM article
WHERE id = 2
  • sql 상세보기 명령문이다. 잘 활용하자.

🔐문제 발생

  • 원하는 게시글만 보고 싶다? 그럼 2 부분에 입력받은 id가 들어가게 바꾸면 되는거 아니야??

🔑 문제 해결

System.out.println("==글 상세보기==");
				System.out.println("상세보기 할 게시글번호 : ");
				int num = sc.nextInt();
String sql = " SELECT * "
							   + " FROM article"
							   + " WHERE id = '" + num + "'";
					
					System.out.println(sql);

					pstmt = conn.prepareStatement(sql);

					rs = pstmt.executeQuery(sql);

					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);

					}
					for (int i = 0; i < articles.size(); i++) {
						System.out.println("번호 : " + articles.get(i).getId());
						System.out.println("등록 날짜 : " + articles.get(i).getRegDate());
					    System.out.println("수정 날짜 : " + articles.get(i).getUpdateDate());
					    System.out.println("제목 : " + articles.get(i).getTitle());
					    System.out.println("내용 : " + articles.get(i).getBody());
				}

🔔 TODO

0개의 댓글