DB에 연결해주는 Driver
동작 원리
1. 새 프로젝트

2. MySQL - JAVA 연결 라이브러리 설치
1. MVN repository에서 라이브러리 찾기

2. mysql버전과 맞는 버전 설치

3. 주소 복사

4. build.gradle 파일에 dependencies에 붙여 넣고 새로 고침

3. MySQL 설정
-- root로 접속
-- DB생성
create database store;
-- store DB 선택
CREATE TABLE store_tb(
id int primary key auto_increment,
name varchar(20),
price int,
qty int
);
insert into store_tb(name, price, qty) values('사과', 1000, 50);
insert into store_tb(name, price, qty) values('딸기', 2000, 50);
commit;
4. JAVA DBConnection 코드 작성

DBConnection
import java.sql.Connection;
import java.sql.DriverManager;
public class DBConnection {
public static Connection getConnection() {
String url = "jdbc:mysql://localhost:3306/store"; // 프로토콜 틀려보고, 포트번호 틀려보고, db이름 틀려보고
String username = "root"; // 아이디 틀려보고
String password = "bitc5600!"; // 비번 틀려보고
try {
Class.forName("com.mysql.cj.jdbc.Driver"); // 동적으로 문자열을 확인하고 객체를 new한다. Driver를 heap에 생성
Connection conn = DriverManager.getConnection(url,username,password); // conn = 프로토콜이 적용된 소켓이라 생각
return conn;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
StoreApp
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StoreApp {
public static void main(String[] args) {
// 1. DB 연결 - 세션 만들어짐
Connection conn = DBConnection.getConnection();
try {
// 2. 버퍼
String sql = "select id, name, price, qty from store_tb where id = ?";
PreparedStatement psmt = conn.prepareStatement(sql); // 버퍼에 쿼리 작성
psmt.setInt(1, 2); // 1 = ?위치 2 = 값
// 3. flush
// result = 테이블 조회 결과 = view
ResultSet result = psmt.executeQuery();
boolean isThere = result.next(); // 커서 1칸 이동
if (isThere) {
int id = result.getInt("id"); // int로 캐스팅
String name = result.getString("name");
int price = result.getInt("price");
int qty = result.getInt("qty");
System.out.println(id + " " + name + " " + price + " " + qty);
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}

5. 한글 깨짐 오류


6. 오류들
Connection conn = DriverManager.getConnection(url, username, password)
- 연결에서 url의 프로토콜이 틀렸을 경우

드라이버를 찾을 수 없음
- 연결에서 url의 호스트가 틀렸을 경우

통신 링크 장애
- 연결에서 url의 포트번호가 틀렸을 경우

통신 링크 장애
- 연결에서 데이터베이스 이름이 틀렸을 경우

알려지지 않은 데이터베이스
- 연결에서 username을 틀렸을 경우

사용자에 대한 접근이 거부
- 연결에서 password가 틀렸을 경우

사용자에 대한 접근이 거부
7. 상품 프로그램 만들기
1. 모델 생성
package model;
// model -> db에 있는 table 데이터를 비슷하게 구현
// view가 새롭게 만들어지면 그 때 그 model을 만들면 된다.
public class Store {
private Integer id;
private String name;
private Integer price;
private Integer qty;
public Store(Integer id, String name, Integer price, Integer qty) {
this.id = id;
this.name = name;
this.price = price;
this.qty = qty;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public Integer getPrice() {
return price;
}
public Integer getQty() {
return qty;
}
@Override
public String toString() {
return "Store{" +
"id=" + id +
", name='" + name + '\'' +
", price=" + price +
", qty=" + qty +
'}';
}
}
2. DAO(Data Access Object) 생성
package dao;
import model.Store;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
// Data Access Object
public class StoreDAO {
private Connection conn;
public StoreDAO(Connection conn) {
this.conn = conn;
}
// 1. 한건 조회
public Store 한건조회(int id) {
try {
// 2. 버퍼
String sql = "select id, name, price, qty from store_tb where id = ?";
PreparedStatement psmt = conn.prepareStatement(sql); // 버퍼에 쿼리 작성
psmt.setInt(1, id); // 1 = ?위치, id = 값
// 3. flush
// result = 테이블 조회 결과 = view
ResultSet result = psmt.executeQuery(); // flush
boolean isThere = result.next(); // 커서 1칸 이동
if (isThere) {
Store model = new Store(
result.getInt("id"),
result.getString("name"),
result.getInt("price"),
result.getInt("qty")
);
return model;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
return null;
}
// 2. 전체 조회
public List 전체조회() {
List<Store> models = new ArrayList();
try {
String sql = "select * from store_tb order by id desc";
PreparedStatement psmt = conn.prepareStatement(sql);
ResultSet result = psmt.executeQuery();
while (result.next()) {
Store model = new Store(
result.getInt("id"),
result.getString("name"),
result.getInt("price"),
result.getInt("qty")
);
models.add(model);
}
return models;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 3. 한건 추가
public void 한건추가(String name, int price, int qty) {
try {
String sql = "insert into store_tb(name, price, qty) values(?, ?, ?)";
PreparedStatement psmt = conn.prepareStatement(sql);
psmt.setString(1, name);
psmt.setInt(2, price);
psmt.setInt(3, qty);
int result = psmt.executeUpdate(); // write (insert, update, delete)
if (result == 0) {
throw new RuntimeException("insert가 실패했습니다.");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 4. 한건 수정
public void 한건수정(String name, int price, int qty, int id) {
try {
String sql = "update store_tb set name = ?, price = ?, qty = ? where id = ?";
PreparedStatement psmt = conn.prepareStatement(sql);
psmt.setString(1, name);
psmt.setInt(2, price);
psmt.setInt(3, qty);
psmt.setInt(4, id);
int result = psmt.executeUpdate();
if (result == 0) {
throw new RuntimeException("니가 준 id가 없다");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 5. 한건 삭제
public void 한건삭제(int id) {
try {
String sql = """
delete from store_tb
where id = ?
""";
PreparedStatement psmt = conn.prepareStatement(sql);
psmt.setInt(1, id);
int result = psmt.executeUpdate();
if (result == 0) {
throw new RuntimeException("id 없다");
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
3. 메인 실행
import dao.StoreDAO;
import model.Store;
import java.sql.Connection;
import java.util.List;
public class StoreApp {
public static void main(String[] args) {
// 1. DB 연결 - 세션 만들어짐
Connection conn = DBConnection.getConnection();
// 2. DAO 연결
StoreDAO dao = new StoreDAO(conn);
// 3. 조회
Store model = dao.한건조회(1);
System.out.println(model);
// 4. 추가
dao.한건추가("감자", 500, 2000);
// 5. 수정
dao.한건수정("감자", 500, 200, 3);
// 6. 한건 삭제
dao.한건삭제(1);
// 7. 전체 조회
List<Store> models = dao.전체조회();
for (Store model : models) {
System.out.println(model);
}
}
}
3. 조회

4. 추가

➡

5. 수정

➡

6. 삭제

➡

7. 전체 조회

Share article