본문 바로가기
개발 언어/JAVA

18. JDBC

by 코헤0121 2024. 4. 1.
728x90
반응형

 

JSP

  • 우선 jar 파일을 구해야한다
  •  
  • 이후는 아래의 것들을 그냥 그대로 이어가면 된다.

JAVA에서 DB연동(JDBC - Java Database Connectivity)

연동 작업 순서!!

  1. Driver Loading : DB연동을 위해서 구현된 라이브러리를 호출 => Class.forName("드라이버 이름")
    • .jar 파일 다운로드
    <classpathentry kind="lib" path="D:/AWSDEVELOP/채현영/mysql-connector-j-8.3.0.jar">
    		<attributes>
    			<attribute name="module" value="true"/>
    		</attributes>
    	</classpathentry>
    
    
  2. DriverManager를 통한 Connection 생성 => DriverManager.getConnection() 메서드를 통해서 Connection 객체 생성
    • getConnection(String url, String user, String password)
      • url : DB연동을 위한 DB주소
      • user : DB 접속 사용자
      • password : DB 접속 사용자의 패스워드
  3. Connection 객체를 통해서 Statement 객체를 생성 => Statement 객체는 SQL을 실행하기 위한 객체. createStatement()로 생성
    • 데이터베이스 연결 객체
  4. SQL 작성 : DB에서 실행할 SQL을 작성
  5. SQL 실행 : Statement 객체 내의 메서드를 실행!
    • executeUpdate() : Insert, Update, Delete 쿼리 사용시 쓰는 메서드 반환 타입이 정수 : 0이면 실패, 1이면 성공
    • executeQuery() : select SQL쿼리를 사용할 경우에 쓰는 메서드 반환 타입이 ResultSet 객체로 전달 받음. ResultSet에 제공하는 메서드를 통해서 결과값을 읽어 올 수 있음. ** ResultSet의 주요 메서드
    1. next() : select 쿼리의 결과값 존재 여부를 확인하는 메서드. 반환 타입 boolean.
    2. getString(String name) : name 컬럼의 문자 타입의 데이터 읽어오기
    3. getInt(String name) : name 컬럼의 정수 타입 데이터 읽어오기
    4. getDouble(String name) : name 컬럼의 실수 타입 데이터 읽어오기

  • VO 클래스 or DTO 클래스
    • VO 클래스(Value Object class) - 객체에 값을 저장한 형태, DB나 데이터 저자 용도 변수들의 모음 연합 → entity DB의 테이블과 똑같은 데이터를 갖고 있는 객체
    • DTO 클래스 (Data transfer object class): 데이터 전송 처리를 위한 값을 저장하는형태의 객체 entity라고도 불림
    • 계층간의 데이터를 전달해주는 용도를 함.
package obj;

public class PersonsVO {
    private int id;
    private String firstName;
    private String lastName;
    private int age;
    private String city;

    public PersonsVO(){    }
    public PersonsVO(int id, String firstname , String lastname, int age, String city){
        this.id = id;
        this.firstName = firstname;
        this.lastName = lastname;
        this.age = age;
        this.city = city;
    }

    public void setAge(int age) {
        this.age = age;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public void setId(int id) {
        this.id = id;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public int getAge() {
        return age;
    }
    public String getCity() {
        return city;
    }
    public String getFirstName() {
        return firstName;
    }
    public int getId() {
        return id;
    }
    public String getLastName() {
        return lastName;
    }
    @Override
    public String toString(){
        return String.format("ID: %d, First Name: %s, Last Name: %s, Age: %d, City: %s", getId(), getFirstName(), getLastName(), getAge(), getCity());

    }
}
  • 멤버변수 선언 필요 - 필드, 속성
    • 자바를 프로그램을 짜다 보면 데이터와 연결되는 부분에 VO를 만든다
    • 기능상으로 변경되면 DAO에서 수정하고
  • DAO 클래스 (Data Acces Object Class)
    • 데이터베이스에 접속해서 데이터의 CRUD 등의 작업을 하는 클래스
    • 일반적으로 다른 프로그램 로직 위에서 동작하기도 하지만 별도의 DAO 클래스를 만들어 사용하기도 한다.
    • → 코드의 유지보수 및 코드의 모듈화를 위해서
    • 보통은 한 개의 테이블 마다 한 개의 DAO를 작성합니다
    • DAO 클래스는 테입ㄹ로부터 데이터를 읽어와서 자바 객체로 변환하거나 자바 객체의 값을 테이블에 저장한다.
    • 때문에 DAO를 구현하면 테이블의 컬럼과 매핑되는 값을 가지고 있는 클래스를 항상 작성해야 한다. 이 클래스를 VO라고 한다.
package obj;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class PersonsDAO {

    //Connection 객체를 생성하기 위한 값
    private String url ="jdbc:mysql://localhost:3306/testdb";
    private String user = "root";
    private String password = "root";

    //데이터 접속을 위한 객체 데이터베이스 연결 객체(Connection 객체)
    Connection conn = null; //비어있는 객체선언.
    Statement stmt = null;
    ResultSet rs = null;

    //생성자 : Connection 객체를 생성
    public PersonsDAO(){
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 2. Connection 객체 생성 - DriverManger.getConnection 이용
            conn = DriverManager.getConnection(url, user, password);
            System.out.println(conn);
            System.out.println("데이터베이스 접속 성공.");
           
           
           
        } catch (ClassNotFoundException e) {
            System.out.println("드라이버 로드 실패");
        }
        catch(SQLException sqle) {
            System.out.println("SQL 연동 오류");
            System.out.println(sqle.getMessage());

        }
    }

    //CRUD 메서드 구현

    //1 데이터 입력 메서드 구현

    public int insert(PersonsVO vo){
        int result = 0;
        String sql = "insert into Persons (firstname, lastname, age, city)"+ "values('"+vo.getFirstName()+"','"+vo.getLastName()+"',"+ vo.getAge()+",'"+vo.getCity()+"')";
       
        return values(sql);
    }

    // 2 전체 데이터 출력 메서드 구현
   
    public List<PersonsVO> allPersons(){
        List<PersonsVO> pList = new ArrayList<>();
       
        String sql = "select * from Persons;";

        try {
            stmt = conn.createStatement();
           
            rs = stmt.executeQuery(sql);
            while(rs.next()) {
                int id = rs.getInt("id");
                String firstname = rs.getString("firstname");
                String lastname = rs.getString("lastname");
                int age = rs.getInt("age");
                String city = rs.getString("city");

                System.out.printf("id : %d, 성 : %s, 이름 : %s, 나이 : %d, 도시 : %s \n",
                        id, firstname, lastname, age, city);
                PersonsVO vo = new PersonsVO(id, firstname, lastname, age, city);
                pList.add(vo);
            }
   
        } catch (SQLException e) {
            System.out.println("SQL 연동 실패");
            System.out.println(e.getMessage());
        }
        finally {
            try {
               if(stmt != null) stmt.close();  
               if (rs!=null) rs.close();            
            } catch (Exception e) {    }
        }

        return pList;
    }

    public PersonsVO selectOne (int id){
        PersonsVO vo = null;
        String sql = String.format("select * from Persons where id = "+id+";");

        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);
            if (rs.next()) {    
               
                int id1 = rs.getInt("id");
                String firstname = rs.getString("firstname");
                String lastname = rs.getString("lastname");
                int age = rs.getInt("age");
                String city = rs.getString("city");
                vo = new PersonsVO(id1, firstname, lastname, age, city);
            }
            else{ System.out.println("없는 데이터입니다");}
   
        } catch (SQLException e) {
            System.out.println("SQL 연동 실패");
            System.out.println(e.getMessage());
        }
        finally {
            try {
               if(stmt != null) stmt.close();  
               if (rs!=null) rs.close();            
            } catch (Exception e) {    }
        }
        return vo;
    }

    public PersonsVO selectOne (String name){
        PersonsVO vo = null;
        String sql ="select * from Persons where lastname like '%"+name+"%' ;";
       
        try {
            stmt = conn.createStatement();
            rs = stmt.executeQuery(sql);    
            if (rs.next()) {    
               
                int id1 = rs.getInt("id");
                String firstname = rs.getString("firstname");
                String lastname = rs.getString("lastname");
                int age = rs.getInt("age");
                String city = rs.getString("city");
                vo = new PersonsVO(id1, firstname, lastname, age, city);
            }
            else{ System.out.println("없는 데이터입니다");}
   
        } catch (SQLException e) {
            System.out.println("SQL 연동 실패");
            System.out.println(e.getMessage());
        }
        finally {
            try {
               if(stmt != null) stmt.close();  
               if (rs!=null) rs.close();            
            } catch (Exception e) {    }
        }
        return vo;
    }

    //3 정보 수정 메서드 구현

    public int update(PersonsVO vo){
        int result = 0;

        String sql = "update Persons set firstname='"+vo.getFirstName()+"', lastname='"+vo.getLastName()+ "', age="+ vo.getAge()+", city='"+vo.getCity()+"' where id = "+vo.getId();
           
        return values(sql);

    }
    //4 정보 삭제 메서드 구현


    public int delete (int id){
        int result = 0;
        String sql = "delete from Persons where id ="+id;
       
        return values(sql);
    }

    public int values(String sql){
        int result =0;
        try {
            stmt = conn.createStatement();
            result = stmt.executeUpdate(sql);
   
        } catch (SQLException e) {
            System.out.println("SQL 연동 실패");
            System.out.println(e.getMessage());
        }
        finally {
            try {
               if(stmt != null) stmt.close();  
               if (rs!=null) rs.close();            
            } catch (Exception e) {    }
        }
        return result;
    }


}

 

main

package I_java;

import java.util.List;
import java.util.Scanner;

import obj.PersonsDAO;
import obj.PersonsVO;

public class I08_personsMain {

    public static void main(String[] args) {
       
        Scanner s = new Scanner(System.in);

        PersonsDAO dao = new PersonsDAO();
        PersonsVO vo = new PersonsVO();
       
        //데이터 추가

        // System.out.println("Persons에 데이터 추가 ");
        // System.out.println("성(lastname) 입력 : ");
        // vo.setLastName(s.next());
        // System.out.println("이름(firstname) 입력 : ");
        // vo.setFirstName(s.next());
        // System.out.println("나이(age) 입력 : ");
        // vo.setAge(s.nextInt());
        // System.out.println("주거지(city) 입력 : ");
        // vo.setCity(s.next());

        // int result = dao.insert(vo); //report 추가

        // if(result!= 0){
        //     System.out.println("레코드 추가 성공");
        // }
        // else{
        //     System.out.println("레코드 추가 실패");
        // }

       
        List<PersonsVO> list = dao.allPersons();

        for(PersonsVO pvo : list){
            pvo.toString();
        }
        System.out.println("특정 id를 가진 Persons 출력");
        System.out.print("id를 입력해주세요");
        int ids = s.nextInt();
        PersonsVO svo = dao.selectOne(ids);
        System.out.println(svo);

        System.out.println("<<수정하기>>");
        System.out.print("특정 id 선택하세요 : ");
        int id2 = s.nextInt();
        PersonsVO uVo = dao.selectOne(id2);
        System.out.print("수정할 성을 입력하세요("+uVo.getLastName()+") : ");
        String lastName = s.next();
        if(!lastName.equals("")) {
            uVo.setLastName(lastName);
        }
        System.out.print("수정할 이름을 입력하세요("+uVo.getFirstName()+") : ");
        String firstName = s.next();
        if(!lastName.equals("")) {
            uVo.setFirstName(firstName);
        }
        System.out.print("수정할 나이을 입력하세요("+uVo.getAge()+") : ");
        int age = s.nextInt();
        if(age != 0 && age >= 0) {
            uVo.setAge(age);
        }
        System.out.print("수정할 도시 입력하세요("+uVo.getCity()+") : ");
        String city = s.next();
        if(!city.equals("")) {
            uVo.setCity(city);
        }

        int result = dao.update(uVo);
        if(result != 0) {
            System.out.println("수정 성공!!!");
        }else {
            System.out.println("수정 실패!!!");
        }

       
        s.close();
    }
}
728x90
반응형

'개발 언어 > JAVA' 카테고리의 다른 글

주니어를 위한 가비지 컬렉터와 메모리 할당 전략  (0) 2025.08.31
고객 관리 프로그램 작성  (0) 2024.03.31
17. Network, 서버 만들기!  (0) 2024.03.28
16. ParallelStream, Thread  (0) 2024.03.27
15. Operator, Stream  (0) 2024.03.27