[Spring Boot] 오라클 DB 연결하기 / JDBC / gradle 라이브러리 추가 / 인코딩/ 커넥션설정

seulki·2022년 11월 27일
0

[springboot]

목록 보기
6/27
post-custom-banner

🎈DB 계정 생성하기!


🎈스프링부트 jdbc , ojdbc6.jar 라이브러리 추가하기

  • build.gradle 클릭

  • dependencies에 링크 추가

implementation 'org.springframework.boot:spring-boot-starter-jdbc'
implementation group: 'com.oracle.database.jdbc', name: 'ojdbc6', version: '11.2.0.4'

  • 라이브러리 가져오기 -> build.gradle 우클릭 -> Gradle -> Refresh Gradle Project 클릭

  • 우측 하단에서 진행상황 확인 가능

  • 빌드가 완료되면 console 창에서 확인



🎈DB 커넥션 설정 정보 수정하기

  • application.properties 클릭

  • 인코딩 설정하기

    #encoding
    server.servlet.encoding.charset=UTF-8
    server.servlet.encoding.force=true
    server.servlet.encoding.enabled=true

  • DBMS 설정하기 -> 자신의 DB정보에 맞게 수정필요

    #dbms
    spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
    spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
    spring.datasource.username=[DB계정 이름]
    spring.datasource.password=[DB계정 비밀번호]

  • JdbcRepository.java
    -> DB 연결을 위해 DataSource 주입받기
public class JdbcMemberRepository implements MemberRepository{

	private final DataSource dataSource;
	
	@Autowired
	public JdbcMemberRepository(DataSource dataSource) {
		this.dataSource = dataSource;
	}
  }
  • 기존 JDBC 방법으로 DB연결하기
public class JdbcMemberRepository implements MemberRepository{

	private final DataSource dataSource;
	
	@Autowired
	public JdbcMemberRepository(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	
	@Override
	public Member save(Member member) {
		String sql="INSERT INTO MEMBER values(member_seq.nextval, ?)";
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = dataSource.getConnection();
			String generatedColums[] = {"ID"};
			pstmt  = conn.prepareStatement(sql, generatedColums);
			pstmt.setString(1, member.getName());
			pstmt.executeUpdate();
			rs = pstmt.getGeneratedKeys();
			
			if(rs.next()) {
				member.setId(rs.getInt(1));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
			
		}
		return member;
	}

	@Override
	public List<Member> findAll() {
		
		String sql = "select * from member";
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		List<Member> members = null;
		try {
			conn = dataSource.getConnection();
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			members =new ArrayList<Member>();
			
			while(rs.next()) {
				Member member = new Member();
				member.setId(rs.getInt("id"));
				member.setName(rs.getString("name"));
				members.add(member);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				rs.close();
				pstmt.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}			
		}
		return members;
	}

}
profile
웹 개발자 공부 중
post-custom-banner

0개의 댓글