사용자 삽입 이미지

1) JDBC 드라이버를 등록한다.

DriverManager에 DBMS 벤더가 제공하는 Driver를 등록하는 단계이다.
Class.forName() 메소드를 사용하는 방법

Class.forName("org.git.mm.mysql.Driver"); //Driver URL

2) DriverManager의 getConnection()을 이용해서 Connection객체를 얻는다.

- Connection이라는 것은 DBMS에 연결된 Session을 의미한다.

Connection객체를 획득하는 방법
Connection connection = DriverManager.getConnection(String jdbcURL, String id,
String password);

JDBC URL 형식 : jdbc://HOST[:PORT]/DBNAME
ID : Database 계정
PASSWORD : Database 계정 패스워드

ex) Connection connection = DriverManager.getConnection("jdbc:mysql://localhost
:3306/test", "user", "user_password");

3) Connection객체의 creatStatement()를 통해 Statement 객체를 얻는다.

- 하나의 Connection 으로 부터 여러개의 Statement 객체의 생성이 가능하다.

Connection connection = DriverManager.getConnection("jdbc:mysql://localhost
:3306/test", "user", "user_password");

Statement stmt1 = conn.createStatement();
ResultSet rs1 = statement.executeQuery("SELECT * FROM addressbook");

Statement stmt2 = conn.createStatement();
ResultSet rs2 = statement.executeQuery("SELECT * FROM addressbook");

SQL문을 실행하기 위한 컨테이너 3가지
Statement 종류 :
Statment,
PreparedStatement : SQL문을 Precompile하여 처리하는 것으로 동일한 형태의
질의를 여러번 반복할 경우 Statement 보다 유리하다.
CallableStatement :Stored Procedure를 처리하는 인터페이스 이다.

4) Statement 객체의 executeQuery(), executeUpdate()를 이용해서 SQL을
데이터베이스 서버에 보낸다.

executeQuery() : SELECT문 처리시 사용
executeUpdate() : UPDATE, DELETE, INSERT 등의 쿼리문 처리시 사용

5) ResultSet 객체의 getXXX()를 통해 SQL문장의 실행 결과를 얻는다.
- Statement 인터페이스의 executeQuery()를 실행하면 ResultSet타입의 객체를 반환한다. 이 객체는 실행된 쿼리문의 결과값과 결과값을 얻을 수 있는 메소드를 제공한다.

데이터를 불러오기 위한 두가지 방법을 제공
1. 쿼리문에서 컬럼의 위치로 검색
String name = resultset.getString(1);
2. 쿼리문의 컬럼 명으로 검색
String name = resultset.getString("name");

6. Statement 객체와 Connection객체의 Close를 호출해서 연결을 닫는다.

- Java는 메모리를 따로 관리하지 않아도 자체적으로 Garbage Collection기능이 있어 사용되지 않는 객체는 자동적으로 처리된다. 그렇지만 JDBC드라이버와 같이 외부 지원되는 드라이버에 대해서는 생성된 객체를 코드 내에서 소멸(close)시키도록 권장하고 있다. 따라서, Database에 접속하여 SQL구문을 모두 수행했다면 close()메소드를 호출해 객체를 모두 소멸시키는 것이 바람직하다.

rs.close();
stmt.close();
conn.close();


사용자 삽입 이미지


Posted by 도야지71
,