백엔드/Database

Jdbc(ojdbc) crud 서비스 클래스 | TIL_136

ran4 2022. 8. 19. 23:23

https://www.youtube.com/playlist?list=PLq8wAnVUcTFWxwoc41CqmwnO-ZyRDL0og

강의를 듣고 정리한 내용입니다


CRUD를 담당하는 NoticeService 생성하기

package명 –> com.newlecture.app.service

이름이 충돌되지 않게 하기 위해 도메인 이름으로 짓는다

-> 그동안 패키지 명을 com.name으로 짓는 이유가 궁금했는데 강의를 통해 알게되었다

 

 

Notice.java

일종의 그릇이 되는 개체 클래스이다

package com.newlecture.app.entity
//클래스 생략
private int id;
private String title;
private String writerId;
private Date regDate;
private String content;
private int hit;
private String files;

 

+ getter setter 추가

이클립스 기준 alt + shift + s를 누르고 generate getter and setter로 추가하면 된다

 

public Notice() { } 생성자 추가

alt + shift + s > Generate Constructor using fields로 생성자를 추가하면 된다 

 

 

 

NoticeService.java

아래의 코드들은 class NoticeService{ } 안에 작성된 메서드이다 

 

 

** 코드를 보기 전 변경된 사항이 있다 **

url 값이 동일하기 때문에 

String url = "jdbc:oracle:thin:@localhost:1521/xe"; 은 클래스 부분에서 선언하여

공통적으로 사용할 수 있도록 바꾸었다

 

똑같이 공통되는 코드지만, 아래의 코드는 사용할 때 마다 선언해야한다 

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection conn = DriverManager.getConnection(url, "test", "****");

 

대신 추후 수정이 편하도록 문자열을 변수로 선언하여 넣어주었다  

public class NoticeService() {
	private String url = "jdbc:oracle:thin:@localhost:1521/xe";
	private String userId = "test";
	private String pwd = "****";
	private String driver = "oracle.jdbc.driver.OracleDriver";
}

 

 

 

1. getList() 메서드 

public List<Notice> getList() throws ClassNotFoundException, SQLException {
		
String sql = "SELECT * from notice";
		
Class.forName(driver); //문자열 값 대신 변수로 대체
Connection conn = DriverManager.getConnection(url, userId, pwd); //문자열 값 대신 변수로 대체
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
		
		
List<Notice> list = new ArrayList<Notice>();
		
while(rs.next()) {
int id = rs.getInt("ID");
String title = rs.getString("TITLE");
String writerId = rs.getString("WRITER_ID");
Date regDate = rs.getDate("REGDATE");
String content = rs.getString("CONTENT");
int hit = rs.getInt("hit");
String files = rs.getString("FILES");
			
Notice notice = new Notice(id, title, writerId, regDate, content, hit, files);

list.add(notice);
			
}
conn.close();
stmt.close();
rs.close();
return list;
}

 

 

2. insert() 메서드 

String title = "Test"; 에서 입력받은 값을 전달받기 위하여

String title = notice.getTitle(); 로 코드가 바뀌었다

나머지는 지난 정리에 적은 내용과 동일하다 

//데이터 추가 
public int insert(Notice notice) throws ClassNotFoundException, SQLException{
//사용자가 입력한 값 전달받기 
String title = notice.getTitle();
String writerId = notice.getWriterId();
String content = notice.getContent();
String files = notice.getFiles();


//연결 설정
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userId, pwd);

String sql = "INSERT INTO notice (" +
"title," + "writer_id," + "content," + "files" + ") VALUES (?, ?, ?, ?)";


PreparedStatement st = conn.prepareStatement(sql); //미리 sql문을 준비하여 실행한다

st.setString(1, "title");
//자료형에 따라 setString setInt setLong 등으로 변경
st.setString(2, "writer_id");
st.setString(3, "content");
st.setString(4, "files");

int result = st.executeUpdate();
System.out.println(result);

st.close(); conn.close();

return result;
}

 

 

3. update() 메서드

위와 마찬가지로 String title = "test"; -> String title = notice.getTitle();로 바뀌었고

int id = 256; -> int id = notice.getId();로 바뀌었다

public int update(Notice notice) throws ClassNotFoundException, SQLException{
String title = notice.getTitle();
String content = notice.getContent();
String files = notice.getFiles();
int id = notice.getId();


Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userId, pwd);


String sql = "UPDATE notice" + " SET" +
" title = ?," + " content = ?," + " files = ?," + " id = ?" + "WHERE ID = ?";
//띄어쓰기에 주의, 공백이 없을경우 쿼리 실행시 오류가 발생할 수 있다

PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, "title");
st.setString(2, "content");
st.setString(3, "files");
st.setInt(4, id); //자료형이 int이기 때문에 큰 따옴표 없이 적는다 


int result = st.executeUpdate();
System.out.println(result);

st.close(); conn.close();
return result;
}

 

 

 

 

4. delete() 메서드

id값을 메서드에서 인수로 받기 때문에

DELETE notice WHERE ID = 256; 코드가 삭제되었다 

public int delete(int id) throws ClassNotFoundException, SQLException {

Class.forName(driver);
Connection conn = DriverManager.getConnection(url, userId, pwd);

String sql = "DELETE notice WHERE ID = ?";
PreparedStatement st = conn.prepareStatement(sql); 
st.setInt(1, id);

int result = st.executeUpdate();
System.out.println(result);

st.close(); conn.close();
return result;
}