Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- python
- fragment identifier
- 쿼드압축 후 개수세기
- pandas
- Java
- 메뉴리뉴얼
- Stack
- 알고리즘
- dfs
- HashSet
- Dynamic Programming
- 어려웠던 문제
- 완전탐색
- 점프와 순간이동
- 순열
- 동적계획법
- 에라토스테네스의 체
- 프로그래머스
- HashMap
- 조합
- 최소공배수
- 보이어무어
- 튜플
- 2017 카카오 코드
- 후위 표기법
- 반복문
- 영문자 확인
- 완전 탐색
- 문자열
- 규칙찾기
Archives
- Today
- Total
csmoon1010의 SW 블로그
JDBC - (부스트코스) 본문
1. 개요
1) JDBC (Java Database Connectivity)란?
- 자바를 이용한 데이터베이스 접속과 SQL 문장의 실행, 그리고 실행 결과로 얻어진 데이터의 핸들링을 제공하는 방법과 절차에 관한 규약
- 자바 프로그램 내에서 SQL문을 실행하기 위한 자바 API
- SQL과 프로그래밍 언어의 통합 접근 중 한 형태
2) 제공 관계
- JAVA : 표준 인터페이스인 JDBC API를 제공
- 데이터베이스 벤더, 또는 기타 써드파티 : JDBC 인터페이스를 구현한 드라이버(driver)를 제공
- 사용자 : 구현된 드라이버를 사용하여 DB 접근
3) 환경 구성
- JDK 설치
- JDBC 드라이버 설치
- Maven에 다음과 같은 의존성을 추가 → MySQL사이트에서 다운로드
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.45</version>
</dependency>
docs.oracle.com/javase/tutorial/jdbc/basics/index.html
2. JDBC 사용 방법
===========================================================================
- import java.sql.*;
- 드라이버를 로드 한다. (DriverManager 이용)
- Class.forName("DB벤더 드라이버 객체"); ex> Class.forName("com.mysql.jdbc.Driver"); - Connection 객체를 생성한다.
- 데이터베이스에 접속
- Connection 인터페이스를 활용해 각각의 벤더가 구현하고 있는 객체로 생성
- ex> Connection con = DriverManager.getConnection(dburl, ID, PWD); - Statement 객체를 생성 및 질의 수행
- SQL 쿼리문 생성 & 실행
- Statement 인터페이스를 활용해 각각의 벤더가 구현하고 있는 객체로 생성
- Statement stmt = con.createStatement(); - SQL문에 결과물이 있다면 ResultSet 객체를 생성한다.
- Select 문인 경우 조회 결과, Insert/Update/Delete인 경우 수행 성공 여부
- 결과셋을 가리킬 수 있는 "레퍼런스 변수" 형태 (rs.next(), rs.getInt(default) 등 이용)
- ex> ResultSet rs = stmt.executeQuery("select no from user"); - 모든 객체를 닫는다.
- 접속 단계의 반대 방향으로
- 클라이언트별로 접속하며 접속 개수는 유한개이므로 수행이 끝나면 반드시 닫아주기!!
- ex> rs.close(); → stmt.close(); → con.close();
===========================================================================
3. 기본 틀 ( dao, dto, client로 분리 )
1) DTO : 생성자, getter, setter, toString()
package kr.or.connect.jdbcexam.dto;
public class Role {
private Integer roleId;
private String description;
public Role() {
}
public Role(Integer roleId, String description) {
super();
this.roleId = roleId;
this.description = description;
}
public Integer getRoleId() {
return roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "Role [roleId=" + roleId + ", description=" + description + "]";
}
}
2) DAO : 드라이버, Connection, Statement, ResultSet을 이용해 DB 접근
package kr.or.connect.jdbcexam.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import kr.or.connect.jdbcexam.dto.Role;
public class RoleDao {
private static String dburl = "jdbc:mysql://localhost:3306/webstudy?serverTimezone=Asia/Seoul&useSSL=false";
private static String dbUser = "csmoon";
private static String dbpasswd = "1010";
public List<Role> getRoles(){
List<Role> list = new ArrayList<>();
try {
Class.forName("com.mysql.jdbc.Driver"); //드라이버 로드
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String sql = "SELECT role_id, description FROM role ORDER BY role_id DESC";
try(Connection conn = DriverManager.getConnection(dburl, dbUser, dbpasswd);
PreparedStatement ps= conn.prepareCall(sql);) { //try-with-resource : Connection, Statement
try(ResultSet rs = ps.executeQuery()){ //ResultSet
while(rs.next()) {
int id = rs.getInt("role_id");
String description = rs.getString(2);
Role role = new Role(id, description);
list.add(role);
}
} catch(Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return list;
}
}
- try-with-resource
try에 Connection, PreparedStatement 리소스를 얻어오는 코드를 포함
→ 알아서 close 처리하므로 코드의 복잡함을 줄일 수 있다!!
'웹 > 백엔드' 카테고리의 다른 글
Spring Core - (부스트코스) (0) | 2021.04.11 |
---|---|
WEB API - (부스트코스) (0) | 2021.04.09 |
Maven - (부스트코스) (0) | 2021.04.08 |
JSP의 JSTL & EL - (부스트코스) (0) | 2021.04.05 |
JSP의 Scope - (부스트코스) (0) | 2021.03.30 |
Comments