Java Eclipse & MySQL 연동
- 기본 세팅 (프로젝트에 JDBC 드라이버 연결) = Eclipse에 Project 생성 -> Project 선택 후 마우스 우클릭 -> Build Path -> Configure ~ 클릭 -> Add External JARS -> JDBC 파일 선택 후 Apply (JDBC 파일은 따로 다운받아야 함)
- Eclipse에 MySQL Driver 연결 -> DB 연결 -> SQL 문장 객체 생성 -> SQL 문장 실행 객체 생성 -> 데이터 활용 -> DB 종료
MVC 패턴 + DB 연동
DTO(Data Transfer Object)
- 데이터 전송 객체
- DTO는 getter, setter, toSpring, constructor(생성자)에 대한 정의로만 구성
구성
- 연결할 DB에 있는 테이블의 컬럼에 대한 필드 생성
- 기본 생성자 생성
- 생성한 필드를 이용하는 사용자 정의 생성자 생성 (generate constructor using field)
- 생성한 필드에 대한 getter, setter 생성
- 생성한 필드에 대한 toSpring 생성
- 필드를 제외하고 Eclipse에서 마우스 우클릭 - source에서 편리하게 생성 가능
DAO(Data Access Object)
- 데이터 접근 객체
- 쿼리문을 이용한 CRUD 실행을 담당
- DAO의 모든 메소드는 DB 관련 작업만을 담담
※ DB로 MySQL을 이용하는 경우
- MySQL 드라이버 연결 -> MySQL 연결 -> SQL 문장 객체 생성 -> 쿼리문 실행 객체 생성
-> 쿼리문 실행시킴으로써 CRUD -> DB 연결 종료
필수 클래스
- Connection = DB와의 연결을 위해
- PreparedStatement = 쿼리문 실행 및 결과값 반환을 위해
※ Execute = 쿼리문 실행 결과 Boolean(true/false) 타입으로 반환
※ ExecuteQuery = ResultSet 객체를 반환 (SELECT문에서만 적용가능!!)
- SELECT만이 결과값으로 DB데이터를 불러와 ResultSet 객체로 반환함
※ ExecuteUpdate = 쿼리문이 반영된 레코드 수를 int 타입으로 반환 (Create나 Drop의 경우에는 -1 반환)
- ResultSet = 하나의 레코드에 대한 여러 value들을 반환하는 경우 여러값들을 객체에 담기 위해
- ArrayList = 하나가 아닌 두 개이상의 레코드에 대한 value(s)를 반환하는 경우를 위해
예시 코드
Eclipse에 MySQL Driver 연결
package dept.util;
import java.sql.Connection; // MySQL 연결에 필요
import java.sql.DriverManager; // MySQL 연결시에 필요한 DB명, 아이디, 비밀번호를 받아 적용시키기 위해 필요
import java.sql.ResultSet; // 쿼리 수행 결과를 불러오기 위해 필요
import java.sql.SQLException;
import java.sql.Statement; // 쿼리 수행을 위해 필요
public class DBUtill {
// step01
// MySQL Driver 연결
static {
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // com.mysql.cj.jdbc.Driver = MySQL Driver에 대한 기본값
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
// DB 연결 메소드
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/scott?serverTimezone=Asia/Seoul", "scott", "tiger");
}
// getConnection의 기본 인자 = [jdbc:mysql://localhost주소/DB명?serverTimezone=Asia/Seoul, DB명, 비밀번호]
// 자원 반환 (실행한 반대 순서로 close를 실행해줘야함 - 후입선출)
public static void close(ResultSet rset, Statement stmt, Connection con) {
try {
if(rset != null) {
rset.close();
}
if(stmt != null) {
stmt.close();
}
if(con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(Statement stmt, Connection con) {
try {
if(stmt != null) {
stmt.close();
}
if(con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
DTO
package blood.transfusion.dto;
public class PeopleDTO {
private String id; // 프로젝트내 ID
private String name; // 이름
private int age; // 나이
private String sex; // 성별
private String bloodType; // 혈액형타입
public PeopleDTO() {}
public PeopleDTO(String id, String name, int age, String sex, String bloodType) {
super();
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
this.bloodType = bloodType;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getSex() {
return sex;
}
public String getBloodType() {
return bloodType;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("[아이디 : ");
builder.append(id);
builder.append(", 이름 : ");
builder.append(name);
builder.append(", 나이 : ");
builder.append(age);
builder.append(", 성별 : ");
builder.append(sex);
builder.append(", 혈핵형 : ");
builder.append(bloodType);
return builder.toString();
}
}
DAO
package blood.transfusion.model;
import java.sql.Connection; // DB와의 연결을 위해
import java.sql.PreparedStatement; // 쿼리문 실행 및 결과값 반환을 위해
import java.sql.ResultSet; // 하나의 레코드에 대한 여러값 반환하는 경우 여러값들을 객체에 담기 위해
import java.sql.SQLException;
import java.util.ArrayList; // 하나가 아닌 두 개이상의 레코드에 대한 결과값들을 반환하는 경우를 위해
import blood.transfusion.dto.PeopleDTO;
import blood.transfusion.util.DBUtil;
public class PeopleDAO {
public static boolean addPeople(PeopleDTO people) throws SQLException{
Connection con = null;
PreparedStatement pstmt = null;
try {
// DB 연결 객체
con = DBUtil.getConnection();
// 쿼리 실행 및 결과 반환 객체
pstmt = con.prepareStatement("insert into people values(?, ?, ?, ?, ?)");
pstmt.setString(1, people.getId());
pstmt.setString(2, people.getName());
pstmt.setInt(3, people.getAge());
pstmt.setString(4, people.getSex());
pstmt.setString(5, people.getBloodType());
// executeUpdate() = 쿼리문이 적용된 레코드의 수 반환 (CREATE나 DROP의 경우에는 -1 반환)
int result = pstmt.executeUpdate();
if(result == 1){
return true;
}
}finally{
DBUtil.close(con, pstmt);
}
return false;
}
// 수정
// 사람 id로 이름 수정하기
public static boolean updatePeople(String peopleId, String name) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DBUtil.getConnection();
pstmt = con.prepareStatement("update people set name=? where People_id=?");
pstmt.setString(1, name);
pstmt.setString(2, peopleId);
int result = pstmt.executeUpdate();
if (result == 1) {
return true;
}
} finally {
DBUtil.close(con, pstmt);
}
return false;
}
// sql - delete from People where People_id=?
public static boolean deletePeople(String peopleId) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
try {
con = DBUtil.getConnection();
pstmt = con.prepareStatement("delete from people where People_id=?");
pstmt.setString(1, peopleId);
int result = pstmt.executeUpdate();
if (result == 1) {
return true;
}
} finally {
DBUtil.close(con, pstmt);
}
return false;
}
// id로 해당 사람의 모든 정보 반환
public static PeopleDTO getPeople(String peopleId) throws SQLException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
PeopleDTO people = null;
try {
con = DBUtil.getConnection();
pstmt = con.prepareStatement("select * from people where People_id=?");
pstmt.setString(1, peopleId);
rset = pstmt.executeQuery(); // executeQuery() = 쿼리문 결과값을 ResultSet 객체에 담아줌
if (rset.next()) {
people = new PeopleDTO(rset.getString(1), rset.getString(2), rset.getInt(3), rset.getString(4), rset.getString(5));
}
} finally {
DBUtil.close(con, pstmt, rset);
}
return people;
}
// 모든 사람 검색해서 반환
// sql - select * from People
public static ArrayList<PeopleDTO> getAllPeople() throws SQLException {
Connection con= null;
PreparedStatement pstmt = null;
ResultSet rset = null;
ArrayList<PeopleDTO> list = null;
try {
con = DBUtil.getConnection();
pstmt = con.prepareStatement("select * from people");
rset = pstmt.executeQuery();
list = new ArrayList<PeopleDTO>();
while(rset.next()) {
list.add(new PeopleDTO(rset.getString(1), rset.getString(2), rset.getInt(3), rset.getString(4), rset.getString(5)));
}
}finally {
DBUtil.close(con, pstmt, rset);
}
return list;
}
}
SELECT 쿼리 실행 (결과값 한 개 -> DTO 객체 이용)
public static Dept getDept(int deptno) throws SQLException {
Connection con = null;
Statement stmt = null;
ResultSet rset = null;
Dept dept = null;
try {
// step02 - DB 연결 객체
con = DBUtill.getConnection();
// step03 - 쿼리 실행 객체
stmt = con.createStatement();
// step04 - 쿼리 실행 결과 객체
rset = stmt.executeQuery("SELECT * FROM dept;");
// step05 - 데이터 활용 (CRUD)
// 결과값이 있으면 dept 객체(Dept(int deptno, String dname, String loc))에 저장
if(rset.next()) {
dept = new Dept(rset.getInt("deptno"), rset.getString("dname"), rset.getString("loc"));
}
} finally {
// step06
// DB 종료 (후입선출로 종료)
DBUtill.close(rset, stmt, con);
}
System.out.println(dept);
return dept;
}
SELECT 쿼리 실행 (결과값 두 개 이상 -> 구성 원소가 DTO 객체인 ArrayList 이용)
public static ArrayList<Dept> getAllDept() throws SQLException {
// 필요한 객체들 생성(con -> stmt -> rset)
Connection con = null;
Statement stmt = null;
ResultSet rset = null;
ArrayList<Dept> allDept = null; // 결과값이 여러개이니 결과값을 저장할 ArrayList 객체 생성
try {
// step02 - DB 연결 객체
con = DBUtill.getConnection();
// step03 - 쿼리 실행 객체
stmt = con.createStatement();
// step04 - 쿼리 실행 결과 객체
rset = stmt.executeQuery("SELECT * FROM dept;");
allDept = new ArrayList<Dept>();
// step05 - 데이터 활용 (CRUD)
// 쿼리 실행 결과가 없을 때까지 데이터를 추가하는 과정 반복
while(rset.next()) {
allDept.add(new Dept(rset.getInt("deptno"), rset.getString("dname"), rset.getString("loc")));
}
} finally {
// step06
// DB 종료 (후입선출로 종료)
DBUtill.close(rset, stmt, con);
}
return allDept;
}
'빅데이터 부트캠프 > Java' 카테고리의 다른 글
빅데이터 부트캠프 74일차 (Java Web) (0) | 2022.10.24 |
---|---|
빅데이터 부트캠프 74일차 (Java) (0) | 2022.10.24 |
빅데이터 부트캠프 68일차 (0) | 2022.10.14 |
빅데이터 부트캠프 67일차 (0) | 2022.10.13 |
빅데이터 부트캠프 66일차 (0) | 2022.10.12 |
댓글