JDBC

JDBC 기본구조

코드사냥꾼 2019. 11. 10. 22:17

[ Connection ]

자바프로그램과 데이터베이스를 연결하여 사용하기 위해서는 무조건 Connection 객체가 필요하다.  특정 SQL 문장을 정의하고 실행시킬 수 있는 Statement 객체를 생성할 때 Connection 객체를 이용한다.

	public static void main(String[] args) throws SQLException {
		// 0. 객체생성
		Connection con = null;
		Statement stmt = null;
		ResultSet rs = null;

		// 1. 드라이버 등록
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
			System.out.println("[드라이버 등록 성공]");

			// 2. db 연결 = connection 객체를 사용한다
			// @127.0.0.1 = localhost
			String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
			String id = "KH";
			String pw = "KH";

			con = DriverManager.getConnection(url, id, pw);

			System.out.println("[오라클 연결 성공]");

			// 3. 연결된 db정보로 statement 객체 생성
			stmt = con.createStatement();

			// 4. 쿼리문 작성 및 실행
			String sql = "SELECT * FROM MYTEST";
			rs = stmt.executeQuery(sql);

			// 5. 결과값 출력
			while (rs.next()) {
		    System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
              rs.close();
              stmt.close();
              con.close();
	}