DTO

DTO
게시글(Board)에 대한 데이터를 담는 DTO

package swing0619;


public class BoardDto {
	private int num;
	private String writer;
	private String title;
	private String content;
	private String regtime;
	private int hits;
	
	

	public BoardDto(int num, String writer, String title, String content) {
		super();
		this.num = num;
		this.writer = writer;
		this.title = title;
		this.content = content;

	}
	
	
	
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	public String getWriter() {
		return writer;
	}
	public void setWriter(String writer) {
		this.writer = writer;
	}
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public String getContent() {
		return content;
	}
	public void setContent(String content) {
		this.content = content;
	}
	public String getRegtime() {
		return regtime;
	}
	public void setRegtime(String regtime) {
		this.regtime = regtime;
	}
	public int getHits() {
		return hits;
	}
	public void setHits(int hits) {
		this.hits = hits;
	}



	@Override
	public String toString() {
		return "BoardDto [num=" + num + ", writer=" + writer + ", title=" + title + ", content=" + content
				+ ", regtime=" + regtime + ", hits=" + hits + "]";
	}




	
	
	
	
}

 

DAO

DAO
게시판과 데이터베이스 간의 상호작용을 담당

package swing0619;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;



public class BoardDao {
	// 데이터베이스 연결을 수행하는 메서드
	Connection getConnection() throws ClassNotFoundException, SQLException {
		Class.forName("org.mariadb.jdbc.Driver");
        Connection conn = DriverManager.getConnection(
                    "jdbc:mariadb://localhost:3307/jspdb", "root", "maria");
        return conn;
	}
	// selectList() 메서드: 데이터베이스에서 게시글 목록을 조회하는 메서드
	// getConnection()을 호출하여 데이터베이스 연결을 얻고, Statement 객체를 생성하여 SQL 쿼리를 실행합니다. 
	// 조회 결과를 ArrayList<BoardDto>에 담아 반환
	ArrayList<BoardDto> selectList() throws ClassNotFoundException, SQLException {
		Connection conn = this.getConnection();
		ArrayList<BoardDto> list = new ArrayList<>();
		 Statement stmt = conn.createStatement();
	        ResultSet rs 
	        	= stmt.executeQuery(
	        	"select num,writer,title,content from board");
	        while (rs.next()) {
	        	int num = rs.getInt("num");
	        	String writer = rs.getString("writer");
	        	String title = rs.getString("title");
	        	String content = rs.getString("content");
	        	BoardDto dto 
	        		= new BoardDto(num, writer, title, content);
	        	// arrayList에 넣으시오.
	        	list.add(dto);
	}			
	        return list;
}
	public String getCurrentTime() { // 현재 시각을 문자열 형태로 반환하는 메서드
		//현재 시각을 문자열 형태로 반환하는 코드
		return LocalDate.now()+" " // 현재 날짜를 가져옴
				+LocalTime.now().toString().substring(0, 8);
	}
		// 게시글을 데이터베이스에 추가하는 메서드
		int insertOne(BoardDto dto) throws ClassNotFoundException, SQLException {
			Connection conn = this.getConnection();
			Statement stmt = conn.createStatement();
			String sql = String.format("insert into board(writer,title,content,regtime,hits)"
					+ " values ('%s','%s','%s','%s',0)" , dto.getWriter(), dto.getTitle(), 
													dto.getContent(), this.getCurrentTime());
			System.out.println(sql);
			return stmt.executeUpdate(sql);
		}
		
		// 게시글 데이터베이스에 삭제하는 메서드
		int delete(int num) throws ClassNotFoundException, SQLException {
		    Connection conn = this.getConnection();
		    Statement stmt = conn.createStatement();
		    String sql = String.format("delete from board where num = %d", num);
		    return stmt.executeUpdate(sql);
		}
		
		
		// 게시글 테이터베이스에 업데이트 메서드
		int update(BoardDto dto) throws ClassNotFoundException, SQLException {
		    Connection conn = this.getConnection();
		    Statement stmt = conn.createStatement();
		    String sql = String.format("update board set writer = '%s', title = '%s', content = '%s' WHERE num = %d",
		            dto.getWriter(), dto.getTitle(), dto.getContent(), dto.getNum());
		    return stmt.executeUpdate(sql);
		}


		
		
}

 

현재 시각을 출력하는 getCurrentTime() 메서드 정의

package swing0619;

import java.time.LocalDate;
import java.time.LocalTime;

public class Ex1 {

	public static void main(String[] args) {
		Ex1 ex = new Ex1();
		String str = ex.getCurrentTime();
		System.out.println(str);
	}
	public String getCurrentTime() {
		//현재 시각을 문자열 형태로 반환하는 코드
		return LocalDate.now()+" "
				+LocalTime.now().toString().substring(0, 8);
	}

}

 

데이터베이스에서 게시글 목록을 조회하여 리스트에 저장하고 출력하는 코드

package swing0619;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

public class Ex2 {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		ArrayList<BoardDto> list = new ArrayList<>();
		Class.forName("org.mariadb.jdbc.Driver");
        Connection conn = DriverManager.getConnection(
                    "jdbc:mariadb://localhost:3307/jspdb", "root", "maria");
        Statement stmt = conn.createStatement();
        ResultSet rs 
        	= stmt.executeQuery(
        	"select num,writer,title,content from board");
        while (rs.next()) {
        	int num = rs.getInt("num");
        	String writer = rs.getString("writer");
        	String title = rs.getString("title");
        	String content = rs.getString("content");
        	BoardDto dto 
        		= new BoardDto(num, writer, title, content);
        	// arrayList에 넣으시오.
        	list.add(dto);
        }
        //arrayList에서 객체 꺼내어 출력하기
        for (BoardDto dto : list) {
        	System.out.println(dto);
        }
	}

}
<출력>
BoardDto [num=3, writer=ss, title=ddd, content=www, regtime=null, hits=0]
BoardDto [num=4, writer=zz, title=dd, content=sss, regtime=null, hits=0]
BoardDto [num=5, writer=zz, title=dd, content=sss, regtime=null, hits=0]
BoardDto [num=6, writer=zz, title=dd, content=sss, regtime=null, hits=0]
BoardDto [num=11, writer=김티오, title=제목12, content=내용12, regtime=null, hits=0]
BoardDto [num=12, writer=김티오, title=제목12, content=내용12, regtime=null, hits=0]

 

Select 호출

BoardDao 클래스의 selectList() 메서드를 호출하여 게시글 목록을 출력하는 코드

package swing0619;

import java.sql.SQLException;
import java.util.ArrayList;

// BoardDao 클래스의 selectList() 메서드를 호출하여 게시글 목록을 출력하는 코드
public class Ex3 {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		BoardDao dao = new BoardDao();
		ArrayList<BoardDto> list =  dao.selectList();
		for(BoardDto dto : list) {
			System.out.println(dto);
		}
	}

}
<결과>
BoardDto [num=3, writer=ss, title=ddd, content=www, regtime=null, hits=0]
BoardDto [num=4, writer=zz, title=dd, content=sss, regtime=null, hits=0]
BoardDto [num=5, writer=zz, title=dd, content=sss, regtime=null, hits=0]
BoardDto [num=6, writer=zz, title=dd, content=sss, regtime=null, hits=0]
BoardDto [num=11, writer=김티오, title=제목12, content=내용12, regtime=null, hits=0]
BoardDto [num=12, writer=김티오, title=제목12, content=내용12, regtime=null, hits=0]

 

Insert 메서드 호출

BoardDao 클래스의 insertOne() 메서드를 호출하여 게시글을 추가하는 코드

package swing0619;

import java.sql.SQLException;
	


public class Ex4 {

	public static void main(String[] args) throws ClassNotFoundException, SQLException {
		BoardDao dao = new BoardDao();
		
		BoardDto dto = new BoardDto(0, "김티오", "제목12", "내용12");
		
		int res = dao.insertOne(dto);
		if(res == 1) {
			System.out.println("DB 입력 성공");
		}else {
			System.out.println("DB 입력 실패");
		}
	}

}

 

Delete 메소드 호출

package swing0619;

import java.sql.SQLException;

public class Ex5 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        BoardDao dao = new BoardDao();

        int num = 10; // 삭제할 게시글의 num 값을 설정

        // 게시글 삭제
        int res = dao.delete(num);

        if (res == 1) {
            System.out.println("게시글 삭제 성공");
        } else {
            System.out.println("게시글 삭제 실패");
        }
    }
}

 

Update 호출

package swing0619;

import java.sql.SQLException;

public class Ex6 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        BoardDao dao = new BoardDao();
        BoardDto dto = new BoardDto(2, "변경", "변경제목", "변경내용");
        
        

        // 게시글 수정
        int res = dao.update(dto);

        if (res == 1) {
            System.out.println("게시글 수정 성공");
        } else {
            System.out.println("게시글 수정 실패");
        }
    }
}

+ Recent posts