JDBC Driver는 DBMS 종류에 맞게 사용해야 한다.
테이블 이름이 아닌 DB의 이름을 알아야 한다.
2 -> 1 -> 4 -> 3
매개변수화된 SQL 문의 ? 순번은 1번부터 시작한다
next() 메소드는 커서를 다음 행으로 이동시키는데, 이동한 행에 데이터가 있으면 true를, 없으면 false를 리턴한다.
last 행까지는 true를 리턴하고 afterLast 행으로 이동하면 false를 리턴한다.
함수 호출 문자열로 "{ ? = call 함수명(?, ?, …) }"을 사용한다
롤백은 모든 작업을 취소하고 실행 전으로 되돌아간다.
Board.java
import java.util.Date;
import java.util.Objects;
public class Board {
private int bno;
@Override
public String toString() {
return "Board{" +
"bno=" + bno +
", btitle='" + btitle + '\'' +
", bcontent='" + bcontent + '\'' +
", bwriter='" + bwriter + '\'' +
", bdate=" + bdate +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Board board = (Board) o;
return bno == board.bno && btitle.equals(board.btitle) && bcontent.equals(board.bcontent) && bwriter.equals(board.bwriter) && bdate.equals(board.bdate);
}
@Override
public int hashCode() {
return Objects.hash(bno, btitle, bcontent, bwriter, bdate);
}
public int getBno() {
return bno;
}
public void setBno(int bno) {
this.bno = bno;
}
public String getBtitle() {
return btitle;
}
public void setBtitle(String btitle) {
this.btitle = btitle;
}
public String getBcontent() {
return bcontent;
}
public void setBcontent(String bcontent) {
this.bcontent = bcontent;
}
public String getBwriter() {
return bwriter;
}
public void setBwriter(String bwriter) {
this.bwriter = bwriter;
}
public Date getBdate() {
return bdate;
}
public void setBdate(Date bdate) {
this.bdate = bdate;
}
public Board(int bno, String btitle, String bcontent, String bwriter, Date bdate) {
this.bno = bno;
this.btitle = btitle;
this.bcontent = bcontent;
this.bwriter = bwriter;
this.bdate = bdate;
}
public Board() {
}
private String btitle; private String bcontent; private String bwriter; private Date bdate;
}
User.java
import java.util.Objects;
public class User {
@Override
public String toString() {
return "User{" +
"userId='" + userId + '\'' +
", userName='" + userName + '\'' +
", userPassword='" + userPassword + '\'' +
", userAge=" + userAge +
", userEmail='" + userEmail + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return userAge == user.userAge && userId.equals(user.userId) && userName.equals(user.userName) && userPassword.equals(user.userPassword) && userEmail.equals(user.userEmail);
}
@Override
public int hashCode() {
return Objects.hash(userId, userName, userPassword, userAge, userEmail);
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public int getUserAge() {
return userAge;
}
public void setUserAge(int userAge) {
this.userAge = userAge;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public User(String userId, String userName, String userPassword, int userAge, String userEmail) {
this.userId = userId;
this.userName = userName;
this.userPassword = userPassword;
this.userAge = userAge;
this.userEmail = userEmail;
}
public User() {
}
private String userId;
private String userName;
private String userPassword;
private int userAge;
private String userEmail;
}
BoardExample.java
import java.sql.*;
import java.util.Scanner;
public class BoardExample {
private Scanner scanner = new Scanner(System.in);
private Connection conn;
public BoardExample() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/thisisjava", "root", "lovesickgirl");
} catch (Exception e) {
e.printStackTrace();
exit();
}
}
public void list() {
System.out.println();
System.out.println("[게시물 목록]");
System.out.println("-------------------------------------------------------------------");
System.out.printf("%-6s%-12s%-16s%-40s\n", "no", "writer", "date", "title");
System.out.println("-------------------------------------------------------------------");
try {
String sql = "" + "SELECT bno, btitle, bcontent, bwriter, bdate " + "FROM boards " + "ORDER BY bno DESC";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
while (rs.next()) {
Board board = new Board();
board.setBno(rs.getInt("bno"));
board.setBtitle(rs.getString("btitle"));
board.setBcontent(rs.getString("bcontent"));
board.setBwriter(rs.getString("bwriter"));
board.setBdate(rs.getDate("bdate"));
System.out.printf("%-6s%-12s%-16s%-40s \n", board.getBno(), board.getBwriter(), board.getBdate(), board.getBtitle());
}
rs.close();
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
exit();
}
mainMenu();
}
public void mainMenu() {
System.out.println();
System.out.println("-------------------------------------------------------------------");
System.out.println("메인 메뉴: 1.Create | 2.Read | 3.Clear | 4.Join | 5.Exit");
System.out.print("메뉴 선택: ");
String menuNo = scanner.nextLine();
System.out.println();
switch (menuNo) {
case "1" -> create();
case "2" -> read();
case "3" -> clear();
case "4" -> join();
case "5" -> exit();
}
}
public void create() {
Board board = new Board();
System.out.println("[새 게시물 입력]");
System.out.print("제목: ");
board.setBtitle(scanner.nextLine());
System.out.print("내용: ");
board.setBcontent(scanner.nextLine());
System.out.print("작성자: ");
board.setBwriter(scanner.nextLine());
System.out.println("-------------------------------------------------------------------");
System.out.println("보조 메뉴: 1.Ok | 2.Cancel");
System.out.print("메뉴 선택: ");
String menuNo = scanner.nextLine();
if (menuNo.equals("1")) {
try {
String sql = "" + "INSERT INTO boards (btitle, bcontent, bwriter, bdate) " + "VALUES (?, ?, ?, now())";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, board.getBtitle());
pstmt.setString(2, board.getBcontent());
pstmt.setString(3, board.getBwriter());
pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
exit();
}
}
list();
}
public void read() {
System.out.println("[게시물 읽기]");
System.out.print("bno: ");
int bno = Integer.parseInt(scanner.nextLine());
try {
String sql = "" + "SELECT bno, btitle, bcontent, bwriter, bdate " + "FROM boards " + "WHERE bno=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, bno);
ResultSet rs = pstmt.executeQuery();
if (rs.next()) {
Board board = new Board();
board.setBno(rs.getInt("bno"));
board.setBtitle(rs.getString("btitle"));
board.setBcontent(rs.getString("bcontent"));
board.setBwriter(rs.getString("bwriter"));
board.setBdate(rs.getDate("bdate"));
System.out.println("#############");
System.out.println("번호: " + board.getBno());
System.out.println("제목: " + board.getBtitle());
System.out.println("내용: " + board.getBcontent());
System.out.println("작성자: " + board.getBwriter());
System.out.println("날짜: " + board.getBdate());
System.out.println("--------------------------------------------------------------");
System.out.println("보조 메뉴: 1.Update | 2.Delete | 3.List");
System.out.print("메뉴 선택: ");
String menuNo = scanner.nextLine();
if (menuNo.equals("1")) {
update(board);
} else if (menuNo.equals("2")) {
delete(board);
}
}
rs.close();
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
exit();
}
System.out.println();
list();
}
public void update(Board board) {
System.out.println("[수정 내용 입력]");
System.out.print("제목: ");
board.setBtitle(scanner.nextLine());
System.out.print("내용: ");
board.setBcontent(scanner.nextLine());
System.out.print("작성자: ");
board.setBwriter(scanner.nextLine());
System.out.println("-------------------------------------------------------------------");
System.out.println("보조 메뉴: 1.Ok | 2.Cancel");
System.out.print("메뉴 선택: ");
String menuNo = scanner.nextLine();
if (menuNo.equals("1")) {
try {
String sql = "" + "UPDATE boards SET btitle=?, bcontent=?, bwriter=? " + "WHERE bno=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, board.getBtitle());
pstmt.setString(2, board.getBcontent());
pstmt.setString(3, board.getBwriter());
pstmt.setInt(4, board.getBno());
pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
exit();
}
}
list();
}
public void delete(Board board) {
try {
String sql = "DELETE FROM boards WHERE bno=?";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setInt(1, board.getBno());
pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
exit();
}
list();
}
public void clear() {
System.out.println("[게시물 전체 삭제]");
System.out.println("-------------------------------------------------------------------");
System.out.println("보조 메뉴: 1.Ok | 2.Cancel");
System.out.print("메뉴 선택: ");
String menuNo = scanner.nextLine();
if (menuNo.equals("1")) {
try {
String sql = "TRUNCATE TABLE boards";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
exit();
}
}
list();
}
public void join() {
User user = new User();
System.out.println("[새 사용자 입력]");
System.out.print("아이디: ");
user.setUserId(scanner.nextLine());
System.out.print("이름: ");
user.setUserName(scanner.nextLine());
System.out.print("비밀번호: ");
user.setUserPassword(scanner.nextLine());
System.out.print("나이: ");
user.setUserAge(Integer.parseInt(scanner.nextLine()));
System.out.print("이메일: ");
user.setUserEmail(scanner.nextLine());
System.out.println("-------------------------------------------------------------------");
System.out.println("보조 메뉴: 1.Ok | 2.Cancel");
System.out.print("메뉴 선택: ");
String menuNo = scanner.nextLine();
if (menuNo.equals("1")) {
try {
String sql = "" + "INSERT INTO users (userid, username, userpassword, userage, useremail) " + "VALUES (?, ?, ?, ?, ?)";
PreparedStatement pstmt = conn.prepareStatement(sql);
pstmt.setString(1, user.getUserId());
pstmt.setString(2, user.getUserName());
pstmt.setString(3, user.getUserPassword());
pstmt.setInt(4, user.getUserAge());
pstmt.setString(5, user.getUserEmail());
pstmt.executeUpdate();
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
exit();
}
}
list();
}
public void exit() {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
}
}
System.out.println("** 게시판 종료 **");
System.exit(0);
}
public static void main(String[] args) {
BoardExample boardExample = new BoardExample();
boardExample.list();
}
}