국비지원수업
ORACLE[32일차] JDBC사용하여 DB로 연동해보기/ 자바로 SQL문 실행
둥구는 지굴다
2022. 12. 7. 21:48
JDBC 사용해서 오라클 자바 연동
JDBC 드라이버 자바랑 연동하기
- 패키지 상단을 눌러 properties를 누른다.
2. build path를 검색한 뒤 Add Extermal jArs를 누른다.
3. 해당 파일을 클릭한 뒤 apply and close를 누르면 된다.
드라이브 로드 및 Connection 설정하기
따로 클래스를 만들어 getConnection이라는 메서드를 생성해줍니다.
public class DBConnecter {
public static Connection getConnection() {
Connection conn=null;
String url="jdbc:oracle:thin:@localhost:1521:XE";
String user="hr";
String pw="hr";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection(url,user,pw);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch(SQLException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
return conn;
}
}
Connection인터페이스는 특정 데이터베이스와 연결을 하는 역할을 합니다
Connection 인터페이스의 getConnection( ) 메서드는 url, user, password총 세 가지의 정보가 필요하다.
따라서 String에 나의 Oracle 계정에 대해 담아주도록 한다.
Class.forName( ) 메서드는 메모리에 데이터베이스 드라이버 클래스를 로드합니다.
forName() 메소드는 throws ClassNotFoundException 처리합니다.
이렇게 이렇게 연결을 해주는 메서드를 만들어 주었다면 테스트를 해보라 가봅시다.
메인 메서드에서 Test 해보기
public static void main(String[] args) {
Connection conn = DBConnecter.getConnection();
System.out.print("연결확인 :");
System.out.println(conn);
}
성공!
Statement
Statememnt인터페이스는 SQL문을 실행하고 생성된 결과를 반환해줍니다.
ResultSet 인터페이스는 SQL문 실행 시 출력되는 데이터베이스 결과 값을 나타내는 테이블입니다.
PreparedStatement pstmt = null; //sql 실행할 객체를 참조
ResultSet rs = null; // select 쿼리 결과 객체를 참조
String sql = "select * from member_tbl_02";
각각 변수를 생성한 뒤 문자열에 쿼리문을 담아주었습니다.
try {
//sql 명령을 인자로 받아 실행할 객체를 생성하여 pstmt가 참조변수
pstmt = conn.prepareStatement(sql);
//쿼리 실행하고 그 결과를 객체로 생성하여 rs 가 참조변수
rs = pstmt.executeQuery();
//next() 메소드 : 조회 결과 다음행을 참조. 참 또는 거짓
System.out.println("조회가 결과가 있습니까? (첫번째 행) : " + rs.next());
System.out.println("첫번째 컬럼의 값 : " + rs.getInt(1));
} catch (SQLException e) {
e.printStackTrace(); //??
}
- pstmt변수에 conn.prepareStatement(sql) 위에 작성한 쿼리문을 인자로 받아 실행할 객체를 생성했습니다.
- rs=pstmt.excuteQuerry( )는 Statement의 메서드를 통해 실행하는데 쿼리문이 Select문이면 **excuteQuery ( )**메서드를 사용하고
- INSERT, UPDATE, DELETE 등의 DCL문이면 excuteUpdate( ) 메서드를 사용합니다.
- next( ) 메서드는 조회 결과 다음행을 참조합니다. 반환 타입은 boolean입니다.
- getInt, getNString… 메서드는 타입별로 값을 가져올 수 있습니다.
선언한 모든 객체 close( )
finally { // 객체 close.
if (rs != null) { // ResultSet이 null이 아닌 경우에 실행
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pstmt != null) { // Statement이 null이 아닌 경우에 실행
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) { // Connection이 null이 아닌 경우에 실행
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}