JdbcEx
package com.jdbc;
import java.sql.*;
public class JdbcEx {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
//드라이브 검색 실패 가능성이 있으므로 무조건 try/catch로 묶어준다
try {
//2단계 특정 드라이버 검색
//우리가 사용할거는 오라클이니까
Class.forName("oracle.jdbc.driver.OracleDriver");
// System.out.println("드라이브가 정상적으로 검색되었습니다.");
//3단계 : db연결
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:orcl",
"scott",
"tiger");
System.out.println("데이터 베이스 연결 성공");
// 4단계 : 쿼리문 작성
// --Statement Class(정적)
stmt = conn.createStatement();
//SQL 작성하기
StringBuffer sql = new StringBuffer();
sql.append("insert into department "); //맨마지막에 띄어쓰기
sql.append("values(203, '소프트웨어과', 200, '3호관')");
//쿼리문 실행
//execute로 실행이 되고 result에는 몇번추가 됐는지 저장됨
int result = stmt.executeUpdate(sql.toString());
System.out.println(result + " 개 행이 추가 되었습니다.");
}catch(ClassNotFoundException ce){
System.out.println("드라이브 검색 실패 !!");
}catch(SQLException ss){
// ss.printStackTrace();
System.out.println("데이터 베이스 연결 실패!");
}finally {
// 6. 연결해제
//반드시 finally에서 닫아줘야한다.
try {if(stmt != null)stmt.close();}catch(SQLException e) { }
try {if(conn != null) conn.close();}catch(SQLException e) { }
}
}
}