[JAVA] JDBC 연결 및 해제

seonjeong·2023년 2월 9일
0

Java

목록 보기
16/26
post-thumbnail
  • Java DataBase Connectivity
  • Java와 DB연결을 위한 표준 API

JDBC Connection 객체 생성(연결)

  1. Class.forName()

    Class 라는 이름을 가진 클래스는 JVM에서 동작할 클래스들의 정보를 묘사하는 일종의 메타클래스.
    데이터 베이스와 연결할 드라이버 클래스를 찾아서 로드하는 역할.

  2. conn = DriverManager.getConnection(url, id, pw)

    선언한 conn에 생성된 Connection 객체대입

    • url : DB - > Properties > Driver Properties
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 Drive를 찾지 못했습니다");
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection() {
    	// url -> localhost대신 본인ip주소 입력해도 됨 (mysql에서 외부 접속 허용)
    	String url = "jdbc:mysql://localhost:3306/mydb"
        String id = "root";
        String pw = "1234";
    
		Connection conn = null;
		
		try {
			conn = DriverManager.getConnection(url, id, pw);
			System.out.println("Connection Success");
		} catch (SQLException e) {
			System.out.println("db를 연결하지 못했습니다");
			e.printStackTrace();
		}
		return conn;
	}
}

DB 연결 해제

  1. Connection : DB와 연결하기 위한 인터페이스

  2. Statement : SQL을 보내기 위한 통로

  3. ResultSet : SQL문의 결과를 저장하는 객체

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



출처

https://m.blog.naver.com/rnalsttnn2/222099599178
https://yoon990.tistory.com/58

profile
🦋개발 공부 기록🦋

0개의 댓글

관련 채용 정보