인생 디벨로퍼

JDBC를 이용한 자바 dbapp 본문

JAVA Spring

JDBC를 이용한 자바 dbapp

뫄뫙뫄 2023. 2. 13. 18:47
728x90

1. JDBC (Java Database Connectivity) 

: 자바 와 데이터베이스를 연결 해주는 프로그래밍 인터페이스.

 


초기세팅, 테이블 생성

 // https://mvnrepository.com/artifact/mysql/mysql-connector-java
    implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.30'

My SQL Connector java 라이브러리를 추가해준다.

 

create database metadb;

use metadb;

create table product (
 	id int primary key auto_increment,
    name varchar(50),
    price int,
    qty int,
    created_at timestamp
);

MySQL 을 이용해서, 테이블 생성.

 


DB 연결

public class DBConfig {
    public static Connection getConnection() {

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            // new 됨
            Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/metadb", "root", "1234");
            System.out.println("db 연결성공");
            return conn;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

공식 문서 확인후 참고, db 연결

연결 확인 완료!


모델링 해주기~ (get, set) 

public class Product {
    private int id;
    private String name;
    private int price;
    private int qty;
    private Timestamp createdAt;

간단하게 겟터, 셋터 달아주기


상품 등록 (insert)

public class ProductRepository {
    private Connection conn;

public ProductRepository(Connection conn) {
        this.conn = conn;
    }
  
  	public void insert(String name, int price, int qty) throws SQLException {

	// 2. 버퍼에 접근
        String sql = "insert into product(name, price, qty, created_at) values(?,?,?,now())";
        PreparedStatement pstmt = conn.prepareStatement(sql);
        
        // 3. 물음표 완성
        pstmt.setString(1, name);// (물음표의 순서, 이름)
        pstmt.setInt(2, price);
        pstmt.setInt(3, qty);

        // 4. 전송
        int result = pstmt.executeUpdate(); //실행!

        // 5. 응답에 대한 처리
        if (result == 1) {
            System.out.println("insert 되었습니다");
        } else {
            System.out.println("insert 실패");
        }

        // 6. 최종마무리
        pstmt.close();

    }
  • PreparedStatement : statement 업그레이드 버젼이라고 보면됨. (물음표를 받고, 인젝션 공격에 안전)

public class ProductService {

    private ProductRepository productRepository;
    private Connection conn; //db 연결

    public ProductService(ProductRepository productRepository, Connection conn) {
        this.productRepository = productRepository;
        this.conn = conn;
    }

public void 상품등록(String name, int price, int qty) {
        // 트랜잭션 시작
        try {
            productRepository.insert(name, price, qty);
            productRepository.insert(name, price, qty);
            conn.commit();
        } catch (Exception e) {
            e.printStackTrace();
            try {
                conn.rollback();
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
public class DBApp {
    public static void main(String[] args) throws SQLException {
        // 1. 커넥션 가져오기
        Connection conn = DBConfig.getConnection();
        // 2. DAO를 메모리에 올리기
        ProductRepository productRepository = new ProductRepository(conn); // 의존성 주입
        // 3. SERVICE를 메모리에 올리기
        ProductService productService = new ProductService(productRepository, conn);
        // 1,2,3 을 서비스에서 해줌

        productService.상품등록("apple", 2000, 5);

MySQL 에  insert 완료!

 


Select 

    public List<Product> findAll() throws SQLException {
        List<Product> productList = new ArrayList<>();

        // 2. 버퍼 접근
        String sql = "select * from product";
        PreparedStatement pstmt = conn.prepareStatement(sql);

        // 3. 전송
        ResultSet rs = pstmt.executeQuery();
        while (rs.next()) {
            int id = rs.getInt("id");
            String name = rs.getString("name");
            int price = rs.getInt("price");
            int qty = rs.getInt("qty");
            Timestamp createdAt = rs.getTimestamp("created_at");
            Product product = new Product(id, name, price, qty, createdAt);
            productList.add(product);
        }
        return productList;
    }
  • rs.next() : 커서를 다음 행으로 옮김

다음 커서가 없다면 false.

  List<Product> productList = productRepository.findAll();
        for (Product product : productList) {
        System.out.println(product.getName());
        }

 


정리

복잡한 과정들을 

MyBatis 를 이용하면 간단히 할 수 있다.

 

  • 코드가 줄어들고, 가독성이 올라간다
  • SQL 문 코드를 별도의 파일로 관리 하기때문에, 유지보수가 용이하다.

탁월한 매퍼인 MyBatis 에 감사함을 느끼며

이거 너무 재미없다.

 

 

728x90

'JAVA Spring' 카테고리의 다른 글

[Ajax] 좋아요 만들기!  (0) 2023.06.18
[Ajax] 썸네일 수정 contentType 설정  (0) 2023.06.17
SHA-256 해시 함수 코드  (0) 2023.05.12
spring 정리  (0) 2023.05.09
AOP 기본 연습 (1)  (0) 2023.03.14