(오라클+자바) 데이타베이스에 데이타 올리기 - 05







모든걸 하기전에 우리는 준비를 해야한다.

자바를 시작하기 전에
1.먼저 드라이버를 java안에 설치한다.
드라이버란 ob
2.DB의 계정하고 비번을 알아야한다. 그렇게 하면 DB가 연결이 된다.
3.자료를 저장할 테이블을 만든다

자바에 들어가서
4. 데이타의 타입을 정한다 -> 그걸 우린 DTO를 만드는것이다.
5.필드명을 대문자로 한다 (규칙)



먼저 오라클에서 테이블을 만들어서 칼람명을 정해주어야한다.
이게 데이타 저장소의 뼈대이다.


먼저 이렇게 만들어보자




create table GUESTBOOK(
MESSAGE_ID NUMBER(8) CONSTRAINT MES_ID_PK PRIMARY KEY (MESSAGE_ID),
GUEST_NAME VARCHAR2(50) NOT NULL,
GUEST_PWD VARCHAR2(10) NOT NULL,
MESSAGE VARCHAR2(1024) NOT NULL,
);

그럼 저 comment는 무엇일까?

COMMENT ON TABLE guestbook.message_id IS '메세지 번호';
이렇게 comment을 달아주면 된다.

그리고 우리는 eclipse에 가서 DTO를 만들어줘야하는데
DTO가 무엇이냐..? Data Transfer Object 이다.

근데 이걸 왜 만들어줘야하냐? 영어 되는 사람 여기 클릭










package com.guestbookDTO.www;
public class GuestBookVO {
private int messageId;
private String  guestName;
private String password;
private String message;
public GuestBookVO() {
super();
}
public int getMessageId() {
return messageId;
}
public void setMessageId(int messageId) {
this.messageId = messageId;
}
public String getGuestName() {
return guestName;
}
public void setGuestName(String guestName) {
this.guestName = guestName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message; }
}



package com.guestbookDTO.www;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


public class GuestBookDAO {

public void insert(GuestBookVO vo){
             Connection con =null;
             PreparedStatement pstmt =null;
             try {
                     Class.forName("oracle.jdbc.driver.OracleDriver");
                     con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.3:1521:xe", "lucky", "lucky");
                     pstmt = con.prepareStatement("insert into users(message_id, guest_name, gpassword, message) values('?', '?','?','?')");
             
                     System.out.println("The data has been entered");
             }catch(ClassNotFoundException e) {
                     e.printStackTrace();
             }catch(SQLException e) {
             }finally {
                     if(con != null) {try {con.close();} catch (SQLException e) {}finally {} }
                     if(pstmt != null) {try {pstmt.close();} catch (SQLException e) {}finally {} }
                     }
             
}

public void delete() {
//delete guestbook where message_id = ?;
        Connection con =null;
        PreparedStatement pstmt =null;
        try {
                Class.forName("oracle.jdbc.driver.OracleDriver");
                con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.0.3:1521:xe", "lucky", "lucky");
                pstmt = con.prepareStatement("delete from guestbook where message_id='?'");
                System.out.println("The data has been deleted");
        }catch(ClassNotFoundException e) {
                e.printStackTrace();
        }catch(SQLException e) {
        }finally {
                if(con != null) {try {con.close();} catch (SQLException e) {e.printStackTrace();}finally {} }
                if(pstmt != null) {try {pstmt.close();} catch (SQLException e) {e.printStackTrace();}finally {} }
        }
}


package com.guestbookDTO.www; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.List; import java.sql.Connection; public class GuestBookDAO { public int insert(GuestBookVO vo) { int result = 0; // 커넥션 연결 Connection con = null; // PreparedStatement 객체 생성 PreparedStatement pstmt = null; // SQL 문을 나타내는 객체 try { String user = "lucky"; String pwd = "lucky"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(url, user, pwd); pstmt = con.prepareStatement("insert into guestbook values(guestbook_seq.NEXTVAL, ?, ?, ?)"); pstmt.setString(1, vo.getGuestName()); pstmt.setString(2, vo.getPassword()); pstmt.setString(3, vo.getMessage()); result = pstmt.executeUpdate(); Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if(pstmt != null) { try {pstmt.close();}catch(SQLException se) {}finally {} } if(con != null) { try {con.close();}catch(SQLException se) {}finally {} } } return result; // 명령 실행(Query 실행) // 필요한 자료가 무엇인지? 필요한 자료를 담고있는 객체타입이 있는지 확인 후 파라미터 결정 // Query문 => insert guestbook_message(컬럼리스트) values(?, ?, ?, ?); // 실행결과 반환 유무 결정 후 반환 타입 변경 // 사용한 자원의 반납을 위한 구문 사용 } public int delete(GuestBookVO vo) { // delete guestbook_message where message_id = ?; Connection con = null; PreparedStatement pstmt = null; int result =0; try { String user = "lucky"; String pwd = "lucky"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(url, user, pwd); pstmt = con.prepareStatement("delete guestbook where message_id = ?"); pstmt.setInt(1, vo.getMessageId()); result = pstmt.executeUpdate(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if(pstmt != null) { try {pstmt.close();}catch(SQLException se) {}finally {} } if(con != null) { try {con.close();}catch(SQLException se) {}finally {} } } return result; } public int update(int Message_Id, GuestBookVO vo) { // update guestbook_message set message_id = ?, guest_name = ?, guest_password = ?, message = ? where message_id = ?; Connection con = null; PreparedStatement pstmt = null; int result =0; try { String user = "lucky"; String pwd = "lucky"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(url, user, pwd); pstmt = con.prepareStatement("update guestbook set message_id = ?, guest_name = ?, guest_password = ?, message = ? where message_id = ?"); pstmt.setInt(1, vo.getMessageId()); pstmt.setString(2, vo.getGuestName()); pstmt.setString(3, vo.getPassword()); pstmt.setString(4, vo.getMessage()); result = pstmt.executeUpdate(); //executeUpdate()메서드는 정수를 반환한다. } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if(pstmt != null) { try {pstmt.close();}catch(SQLException se) {}finally {} } if(con != null) { try {con.close();}catch(SQLException se) {}finally {} } } return result; } public GuestBookVO selectOne(int Message_Id) { // select * from guestbook_message where message_id = ?; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; GuestBookVO vo = null; try { String user = "lucky"; String pwd = "lucky"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(url, user, pwd); pstmt = con.prepareStatement("select * from guestbook where message_id = ?"); pstmt.setInt(1, vo.getMessageId()); rs = pstmt.executeQuery(); while(rs.next()) { vo = new GuestBookVO(); vo.setMessageId(rs.getInt("Message_Id")); vo.setGuestName(rs.getString("Guest_Name")); vo.setPassword(rs.getString("Guest_Password")); vo.setMessage(rs.getString("Message")); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if(pstmt != null) { try {pstmt.close();}catch(SQLException se) {}finally {} } if(con != null) { try {con.close();}catch(SQLException se) {}finally {} } if(rs != null) { try {rs.close();}catch(SQLException se) {}finally {} } } return vo; } public int selectCount() { // select count(*) from guestbook_message; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; int dataCnt = 0; try { String user = "lucky"; String pwd = "lucky"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(url, user, pwd); pstmt = con.prepareStatement("select count(*) as cnt from guestbook"); rs = pstmt.executeQuery(); while(rs.next()) { dataCnt = rs.getInt("cnt"); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if(pstmt != null) { try {pstmt.close();}catch(SQLException se) {}finally {} } if(con != null) { try {con.close();}catch(SQLException se) {}finally {} } if(rs != null) { try {rs.close();}catch(SQLException se) {}finally {} } } return dataCnt; } public List<GuestBookVO> selectAll() { //select count(*) from guestbook where message_id =?; Connection con = null; PreparedStatement pstmt = null; ResultSet rs = null; List<GuestBookVO> list = null; try { String user = "lucky"; String pwd = "lucky"; String url = "jdbc:oracle:thin:@localhost:1521:xe"; Class.forName("oracle.jdbc.driver.OracleDriver"); con = DriverManager.getConnection(url, user, pwd); pstmt = con.prepareStatement("select * from guestbook"); rs = pstmt.executeQuery(); while(rs.next()) { GuestBookVO vo = new GuestBookVO(); vo.setMessageId(rs.getInt("MessageId")); vo.setGuestName(rs.getString("GuestName")); vo.setPassword(rs.getString("Password")); vo.setMessage(rs.getString("message")); list.add(vo); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException se) { se.printStackTrace(); } catch (Exception ex) { ex.printStackTrace(); } finally { if(pstmt != null) { try {pstmt.close();}catch(SQLException se) {}finally {} } if(con != null) {try {con.close();}catch(SQLException se) {}finally {} } if(rs != null) { try {rs.close();}catch(SQLException se) {}finally {}} } return list; } }





---


new file . html

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=1100"> <!--<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">--> <meta name="description" content="내가 개발한 사이트"/> <meta name="keywords" content="jsp sevlet java database spring development"/> <title>Insert title here</title> </head> <body> <form action="./NewFile.jsp" method="post"> <input type = "text" name = "irum" /><br /> <input type = "text" name = "pwd" /><br /> <textarea name = "msg" id = "" cols = "30" row = "10"></textarea> <input type = "submit" value = "전송"/> </form> </body> </html>


---

new file.jsp

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=1100"> <!--<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no">--> <meta name="description" content="내가 개발한 사이트"/> <meta name="keywords" content="jsp sevlet java database spring development"/> <title>Insert title here</title> </head> <body> <form action="./NewFile.jsp" method="post"> <input type = "text" name = "irum" /><br /> <input type = "text" name = "pwd" /><br /> <textarea name = "msg" id = "" cols = "30" row = "10"></textarea> <input type = "submit" value = "전송"/> </form> </body> </html>


이러면 자바랑 오라클을 연동해서 데이타를 오라클 데이타베이스에 넣을수 있다.

댓글

이 블로그의 인기 게시물

c++ 랜덤 숫자 생성하기 / 컴퓨터 난수 시드 설정

(오라클) View(뷰) + where/order by/like/is/() / in 사용방법 예제

(오라클) Sequence/시퀸스의 활용과 개념