Eclipse에서 JDBC로 MySQL 연동

sua_ahn·2023년 2월 9일
0
post-thumbnail

JDBC

Java DataBase Connectivity
: 데이터베이스를 다루기 위한 자바 API

→ DBMS의 종류와 관계없이 쿼리문으로 데이터 수신 가능

JDBC로 Mysql DB 사용

  1. Dynamic Web Project 생성
  2. 이클립스에 드라이버 파일 등록
    : mysql-connector-java-버전-bin.jar 파일을 lib폴더에 복사붙여넣기
    → Web App Libraries에 동일 파일 표시됨

 

  1. DB Driver Loading (= Driver를 초기화하여 DriverManager에 등록)
    : Class.forName(드라이버 클래스 이름) 사용
    >> MySQL의 드라이버 클래스 이름 확인
public class DBConnection {
    public static void initConnection() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            System.out.println("Driver Loading Success");
        } catch (ClassNotFoundException e) {
            System.out.println("DB Driver 미설치 및 클래스 이름 오류");
            e.printStackTrace();
        }
    }
}

 

  1. DB 연결 (= DriverManager로부터 Connection 객체 얻기)
    : DriverManager.getConnection(url, user, password) 사용
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
.
.
.
public static Connection getConnection() {
    Connection conn = null;
    try {
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "0000");
        System.out.println("Connection Success");
    } catch (SQLException e) {
        System.out.println("DB 연결 오류");
        e.printStackTrace();
    }
    return conn;
}

 

  1. DB 연결 해제
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBClose {
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        try {
            if(conn != null) {
                conn.close();
            }
            if(stmt != null) {
                stmt.close();
            }
            if(rs != null) {
                rs.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

 


MySQL 외부 원격 접속 허용

-- 사용자 생성
create user '아이디'@'허용IP' identified by '패스워드';
-- 권한 할당
grant all privileges on *.* to '아이디'@'허용IP' with grant option;
-- 설정 적용
flush privileges;

cf) 모든 IP 허용 시 '%'

 


JDBC로 DB CRUD

데이터 추가, 삭제, 수정

→ 쿼리문 외 코드 동일

추가

public boolean insert(String col1, String col2 int col3) {
	// insert 쿼리문 작성
    String sql = "insert into 테이블명 "
                + "values(?, ?, ?) ";
	// DB 연결 객체
    Connection conn = DBConnection.getConnection();
    // 쿼리를 실행하는 prepareStatement 객체
    PrepareStatement pstmt = null;
    // 테이블 row의 수
    int count = 0;
    
    try {
    	// 접속 초기화
        pstmt = conn.prepareStatement();
        // 매개변수를 쿼리문에 추가
        pstmt.setString(1, col1);
        pstmt.setString(2, col2);
        pstmt.setInt(3, col3);
        // sql 실행 후 영향을 받은 행의 수 반환
        count = pstmt.executeUpdate(sql);
        System.out.println("DB에 데이터 추가 성공");
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
    	// 연결 해제
        DBClose.close(conn, pstmt, null);
    }
    return count > 0 ? true:false;
}

삭제

public boolean delete(String col1) {
	String sql = "delete from 테이블명 where col1 = ? ";
	.
	.
	.
		pstmt.setString(1, col1);

수정

public boolean update(String col1, String col2 int col3) {
    String sql = "update 테이블명 set col2=?, col3=? where col1=? ";
    .
    .
    .
        pstmt.setString(1, col2);
        pstmt.setString(2, col3);
        pstmt.setString(3, col1);

 

데이터 검색

public List<dto객체> select() {
    String sql = "select * from 테이블명 ";
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    List<dto객체> list = new ArrayList<dto객체>();

    try {
        conn = DBConnection.getConnection();
        pstmt = conn.prepareStatement(sql);
        rs = pstmt.executeQuery();

        while(rs.next()) {
            String _col1 = rs.getString(1);
            String _col2 = rs.getString(2);
            int _col3 = rs.getInt(3);

            dto객체 obj = new dto객체(_col1, _col2, _col3);
            list.add(obj);
        }

    } catch (SQLException e) {
        System.out.println("데이터 검색 실패");
        e.printStackTrace();
    } finally {
        DBClose.close(conn, pstmt, rs);
    }
    return list;
}

>> Eclipse에서 Database 열어서 확인

Eclipse 탐색기 찾기

  • 메뉴 Window - Show View - Data Source Explorer
  • 메뉴 Window - Show View - Other - General - Project Explorer
profile
해보자구

0개의 댓글