KoreaIt Academy/JAVA

26. JDBC [OracleDB과 JAVA연동], MVC모델-(회원가입, 로그인)

hongeeii 2021. 8. 11.
728x90
반응형

자바와 오라클을 연동하기 위해서는 JDBC(JAVA DATABASE CONNECTIVITY)가 필요합니다.

JDBC는 데이터베이스를 자바를 이용하여 조작하기 위한 자바 라이브러리입니다. 

 

여기서는 MVC모델을 이용한 간단한 예제(회원가입, 로그인)를 통해 알아보도록 하겠습니다.

 

이클립스에서 프로젝트를 우클릭 -> build path를 눌러  ojdbc6.jar 파일을 추가해 줍니다.

이렇게 jar파일이 추가된 것을 볼 수 있습니다.

 

연결을 시키기 위해 DBConnection 클래스를 만들어 보겠습니다.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnecter {
	public static Connection getConnection() {
		Connection conn = null;
		try {
			// 연결에 필요한 정보
			String user = "hr";
			String pw = "hr";
			String url = "jdbc:oracle:thin:@localhost:1522:XE";

			// 드라이버를 메모리에 할당
			Class.forName("oracle.jdbc.driver.OracleDriver");

			// 연결된 객체 가져오기
			conn = DriverManager.getConnection(url, user, pw);
		} catch (ClassNotFoundException e) {
			System.out.println("드라이버 로딩 실패");// 드라이버 주소가 잘못됨
		} catch (SQLException e) {
			System.out.println("연결 실패");// url이 잘못됨
		} catch (Exception e) {
			System.out.println("알수 없는 오류");
		}
		return conn;
	}
}

 

Oracle DBMS 에서 USER테이블을 생성해 보겠습니다.

CREATE SEQUENCE [시퀀스명]; 을 통하여 자동으로 중복이 되지 않는 시퀀스를 만들어 줍니다.

사용은 [시퀀스명].NEXTVAL 로 사용하면 됩니다.

 

 

Model 클래스를 만들어줍니다.

public class TBL_USER_VO {
	private int userNumber;
	private String id;
	private String pw;
	private String name;
	private int age;
	private String phoneNumber;
	
	public TBL_USER_VO() {;}
	
	public int getUserNumber() {
		return userNumber;
	}
	public void setUserNumber(int userNumber) {
		this.userNumber = userNumber;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getPw() {
		return pw;
	}
	public void setPw(String pw) {
		this.pw = pw;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public String getPhoneNumber() {
		return phoneNumber;
	}
	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}
	
	
}

 

 

Controller 인 dao클래스를 만들어 줍니다.

Connection conn; // DB와 연결된 객체
PreparedStatement pstm; // SQL문을 담는 객체
ResultSet rs; // SQL문 결과를 담는 객체

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


import vo.TBL_USER_VO;

public class TBL_USER_DAO {
	Connection conn; // DB와 연결된 객체
	PreparedStatement pstm; // SQL문을 담는 객체
	ResultSet rs; // SQL문 결과를 담는 객체

	// 아이디 중복검사
	public boolean checkId(String id) {
		String query = "SELECT COUNT(ID) FROM TBL_USER WHERE ID = ?";
		try {
			conn = DBConnecter.getConnection();
			pstm = conn.prepareStatement(query);
			pstm.setString(1, id);
			rs = pstm.executeQuery();

			rs.next(); // 행
			if (rs.getInt(1)/* 열 */ == 1) {
				return true;
			}

		} catch (SQLException e) {
			System.out.println("checkId SQL문 오류");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (rs != null) {
					rs.close();
				}
				if (pstm != null) {
					pstm.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		return false;
	}

	// 회원가입
	// USERNUMBER NUMBER NOT NULL,
	// ID VARCHAR2(300),
	// PW VARCHAR2(300),
	// NAME VARCHAR2(300),
	// AGE NUMBER,
	// PHONENUMBER VARCHAR2(20),
	public void join(TBL_USER_VO user) {
		String query = "INSERT INTO TBL_USER(USERNUMBER, ID, PW, NAME, AGE, PHONENUMBER) "
				+ "VALUES(USER_SEQ.NEXTVAL, ?, ?, ?, ?, ?)";
		try {
			conn = DBConnecter.getConnection();
			pstm = conn.prepareStatement(query);

			pstm.setString(1, user.getId());
			pstm.setString(2, user.getPw());
			pstm.setString(3, user.getName());
			pstm.setInt(4, user.getAge());
			pstm.setString(5, user.getPhoneNumber());

			pstm.executeUpdate();

		} catch (SQLException e) {
			System.out.println("join SQL문 오류");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (pstm != null) {
					pstm.close();
				}
				if (conn != null) {
					conn.close();
				}
			} catch (SQLException e) {
				throw new RuntimeException(e.getMessage());
			}
		}
	}

	// 로그인
	public boolean login(String id, String pw) {
		String sql = "select * from TBL_USER where id=? and pw =?";
		try {
			conn = DBConnecter.getConnection();
			pstm = conn.prepareStatement(sql);
			pstm.setString(1, id);
			pstm.setString(2, pw);
			rs = pstm.executeQuery();
			if(rs.next()) {
				return true;
			}
			return false;
			
		} catch (SQLException e) {
			System.out.println("login sql문 오류");
		}finally {
			try {
				if(rs!=null) {
					rs.close();
				}
				if(pstm!=null) {
					pstm.close();
				}
				if(conn!=null) {
					conn.close();
				}
			} catch (SQLException e) {
				throw new RuntimeException(e.getMessage());
			}
		}
		
		return false;
	}

}

 

728x90
반응형

추천 글