개발노트

JDBC 드라이버 로딩 및 Connection 생성 본문

Programming/Database

JDBC 드라이버 로딩 및 Connection 생성

dev? 2022. 2. 8. 17:55
반응형

2022.01.20 - [Eclipse] - jar 파일 추가하기 (oracle 18c 기준)

 

jar 파일 추가하기 (oracle 18c 기준)

*jar 파일 위치 > oracle 18c C:\app\사용자명\product\18.0.0\dbhomeXE\jdbc\lib > oracle 11g C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib 1. 프로젝트 선택 > 마우스 우클릭 > Properties 선택 2..

lifeonguide.tistory.com

 


JDBC 관련 클래스
(java.sql 패키지)
DriverManager JVM에서 JDBC전체를 관리하는 클래스
Driver등록, Connection 연결작업 등
Driver DB를 만드는 Vendor(Oracle, MS-SQL, MYSQL등)을 implements하여 DB를 연결할 수 있는 class를 만드는 인터페이스
Connection DB와 연결성을 갖는 인터페이스
Statement SQL문을 실행하는 인터페이스
ResultSet 조회된 결과 데이터를 갖는 인터페이스

 

1. JDBC 드라이버 등록 확인

( * 아래 작업을 수행하기 전에 jar파일을 등록 )

1) MySQL의 JDBC Driver Class를 로딩

2) Class.forName(“driver”)을 이용해서 Driver Class를 로딩하면 객체가 생성되고, DriverManager에 등록

    ex) Class.forName(“com.mysql.jdbc.Driver”)

- Driver 클래스를 찾지 못할 경우, ClassNotFoundException 예외가 발생

public DriverTest() {
	try {
		Class.forName("oracle.jdbc.driver.OracleDriver");
		System.out.println("드라이버 등록 성공");
	} catch (ClassNotFoundException e) {
		System.out.println("드라이버 등록 실패");
		e.printStackTrace();
	}
}

 

2. Connection (DB 연결)

Connection : 데이터베이스와 연결하는 객체

1) DriverManager.getConnection(연결 문자열, DB_ID, DB_PW)으로 Connection 객체를 생성

2) 연결문자열(Connection String) - “jdbc:Driver 종류://IP:포트번호/DB명” 
    ex) jdbc:mysql://localhost:3306/test_db

* ID : DB 아이디
* PW : DB 비밀번호

public Connection getConnection() {
	Connection conn = null;	// 오라클 DB서버와의 접속을 관리하는 클래스

	String url = "jdbc:Driver 종류://IP:포트번호/DB명";
	String userId = "DB 아이디";
	String password = "DB 비밀번호";

	try {
		// DriverManager.getConnection() : OracleDriver 클래스를 이용해서 Oracle DB에 접속을 시도함
		conn = DriverManager.getConnection(url, userId, password);
		System.out.println("접속 성공");
	} catch (SQLException e) {
		System.out.println("접속 실패");
		e.printStackTrace();
	}

	return conn;
}

 

3. SQL 작업 수행

public int deleteMethod() {      
      // DB
      Connection conn = getConnection();
      String sql = "delete from 테이블명 where name = ?";
      int result = 0;
      
      // 보조 스트림 클래스 : Connection 대신 DB와 요청/응답
      PreparedStatement pstmt = null;
      
      try {
         pstmt = conn.prepareStatement(sql);
         pstmt.setString(1, name);
         
         result = pstmt.executeUpdate();
         
      } catch (SQLException e) {
         e.printStackTrace();
      } finally {
			try {
				if (pstmt != null){
					pstmt.close(); // 접속 해제
				}
				if (conn != null){
					conn.close(); // 접속 해제
				}
			} catch (SQLException e) {
				e.printStackTrace();
			}
	  }
      return result;
   }
}

 

public List<Vo> selectMethod() {
	Connection conn = getConnection();

	String sql = "select * from 테이블명";

	List<Vo> list = new ArrayList<Vo>();

	// db에 요청/응답 처리 클래스
	PreparedStatement pstmt = null;
	
	// pstmt가 응답 데이터를 처리하고, 그 결과를 ResultSet 객체에 저장하고 리턴함
	ResultSet rs = null;

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

		// rs.next() : 데이터가 있는지 확인하고 1행의 데이터를 읽어와서
		// true : 데이터 있는 경우, false : 데이터 없는 경우
		while (rs.next()) {
			String name = rs.getString("name");
			int age = rs.getInt("age");
			double height = rs.getDouble("height");
			String logtime = rs.getString("logtime");

			Dto vo = new Dto(name, age, height, logtime);
			list.add(vo);
			
		}
	} catch (SQLException e) {
		e.printStackTrace();
	} finally {
		try {
			if (rs != null)
				rs.close();
			if (pstmt != null)
				pstmt.close();
			if (conn != null)
				conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	return list;
}

 

 


https://allg.tistory.com/20

 

[JDBC] JDBC 드라이버 로딩과 Connection 생성

JDBC 드라이버 로딩과 Connection 생성 1.JDBC 드라이버 로딩 MySQL의 JDBC Driver Class를 로딩합니다. Class.forName(“driver”)을 이용해서 Driver Class를 로딩하면 객체가 생성되고, DriverManager에 등록..

allg.tistory.com

https://fora.tistory.com/71

 

[JDBC] JDBC 관련클래스, 프로그래밍 순서 (Connection, Statement, ResultSet)

JDBC 관련클래스 : java.sql 패키지 DriverManager : JVM에서 JDBC전체를 관리하는 클래스. Driver등록, Connection 연결작업 등 Driver : DB를 만드는 Vendor(Oracle, MS-SQL, MYSQL등)을 implements하여 자신들..

fora.tistory.com

 

반응형

'Programming > Database' 카테고리의 다른 글

테이블 및 컬럼 찾기  (0) 2023.01.08
SQL 함수  (0) 2020.04.27
UNION / INTERSECT / MINUS  (0) 2020.04.27
NVL 함수  (0) 2020.04.27
Join 정리  (0) 2020.04.27