- 드라이버 로딩 ==> 라이브러리를 사용할 수 있게 메모리로 읽어 들이는 작업
Class.forName("oracle.jdbc.driver.OracleDriver");
- DB시스템에 접속하기 ==> 접속이 완료되면 Connection객체가 반환된다.
DriverManager.getConnection()메서드를 이용한다.
- 질의 ==> SQL문장을 DB서버로 보내서 결과를 얻어온다.
(Statement객체 또는 PreparedStatement객체를 이용하여 작업한다.)
- 결과 처리 ==> 질의 결과를 받아서 원하는 작업을 수행한다.
1) SQL문이 select문일 경우
==> select한 결과가 ResultSet 객체에 저장되어 반환된다.
2) SQL문이 insert, update, delete문일 경우
==> 정수값이 반환된다. (이 정수값은 실행에 성공한 레코드 수를 의미한다.)
- 사용한 자원을 반납한다. ==> close() 메서드 이용
JDBC 순서
public static void main(String[] args) {
// DB작업에 필요한 객체변수 선언
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 1. 드라이버 로딩
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2. DB연결 ==> Connection객체 생성
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","JYJ94","java");
// 3. 질의
// 3-1) 실행할 SQL문 작성
String sql = "select * from lprod";
// 3-2) Statement객체 또는 PreparedStatment객체를 생성한다.
// (Connection객체를 이용하여 생성한다.)
stmt = conn.createStatement();
// 3-3) SQL문을 DB서버로 보내서 실행한 결과를 얻어온다.
// (지금은 실행한 SQL문이 select문이기 때문에 select한 결과가 ResultSet객체에 저장되어 반환된다.)
rs = stmt.executeQuery(sql);
// 4. 결과 처리
// rs.next()
// ==> ResultSet객체의 데이터를 가리키는 포인터를 다음 위치로 이동하고 그 곳에 데이터가 있으면 true를 반환한다.
while(rs.next()) {
// 포인터가 가리키는 곳의 자료 가져오기
// 형식1) rs.get자료형이름("컬럼명")
// 형식2) rs.get자료형이름(컬럼번호) ==> 컬럼번호는 1부터 시작한다.
// 형식3) rs.get자료형이름("컬럼의 alias명")
System.out.println("Lprod_id : " + rs.getInt("lprod_id"));
System.out.println("Lprod_gu : " + rs.getString(2));
System.out.println("Lprod_nm : " + rs.getString("lprod_nm"));
System.out.println("---------------------------------------");
}
} catch (SQLException e) {
// TODO: handle exception
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
// 5. 자원 반납(만들어진 순서의 역순)
if(rs!=null)try {rs.close();}catch(SQLException e) {}
if(stmt!=null)try {stmt.close();}catch(SQLException e) {}
if(conn!=null)try {conn.close();}catch(SQLException e) {}
}
}
}
문제) 사용자로부터 Lprod_id값을 입력받아 입력한 값보다 Lprod_id가 큰 자료를 출력하시오.
public class JdbcTest02 {
Scanner scan = new Scanner(System.in);
public static void main(String[] args) {
new JdbcTest02().connect();
}
//사용자에게 입력받는 메서드
private int getId() {
System.out.print("Lprod_id를 입력해주세요 : ");
return scan.nextInt();
}
private void connect() {
// 입력한 값보다 Lprod_id가 큰 자료
// 드라이버 연결
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//이건 왜하는거지?
Class.forName("oracle.jdbc.driver.OracleDriver");
int num = getId();
//드라이버 연결
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "JYJ94", "java");
//sql문 작성
String sql = "select * from lprod where LPROD_ID > " + num;
//쿼리문 보내기
stmt = conn.createStatement();
//결과 추출
rs = stmt.executeQuery(sql);
System.out.println();
System.out.println(" == 결과 출력 ==");
while(rs.next()) {
System.out.println("Lprod_id : " + rs.getInt(1));
System.out.println("Lprod_gu : " + rs.getString(2));
System.out.println("Lprod_nm : " + rs.getString(3));
System.out.println("--------------------");
}
} catch (SQLException e) {
// TODO: handle exception
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(rs!=null)try{rs.close();}catch(SQLException e) {}
if(stmt!=null)try{stmt.close();}catch(SQLException e) {}
if(conn!=null)try{conn.close();}catch(SQLException e) {}
}
}
}
문제) lprod_id값을 2개 입력 받아서 두 값중 작은 값부터 큰 값 사이의 자료를 출력하시오.
public class jdbcTest03 {
public static void main(String[] args) {
// 스캐너 객체
Scanner scan = new Scanner(System.in);
//값 입력받기
System.out.print("첫번째 Lprod값을 입력>");
int num1 = scan.nextInt();
System.out.print("두번째 Lprod값을 입력>");
int num2 = scan.nextInt();
if(num1 > num2) {
int temp = 0;
temp = num2;
num2 = num1;
num1 = temp;
}
int max = Math.max(num1, num2);
int min = Math.min(num1, num2);
// 드라이버 연결
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","JYJ94", "java");
String sql = "select * from lprod where lprod_id between " + min + " and " + max;
//String sql = "select * frmo lprod where lprod_id >= " + min + " and lprod_id <= " + max;
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
System.out.println();
System.out.println(" == 결과출력 ==");
while(rs.next()) {
System.out.println("Lprod_id : " + rs.getInt(1));
System.out.println("Lprod_id : " + rs.getString(2));
System.out.println("Lprod_id : " + rs.getString(3));
System.out.println("========================");
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
계좌번호 추가하기
public class JdbcTest04 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","JYJ94", "java");
stmt = conn.createStatement();
String bankNo;
outer : while(true) {
System.out.println("계좌번호 정보 추가하기");
System.out.print("계좌번호 : ");
bankNo = scan.next();
String sql = "select BANK_NO from bankinfo where bank_no = '" + bankNo+"'";
rs = stmt.executeQuery(sql);
//읽어오기
while(rs.next()) {
if(rs.getString("bank_no")!=null) {
System.out.println("이미 등록된 번호입니다.");
System.out.println("다시 입력해주세요.");
continue outer;
}else break outer;
}
}
System.out.print("은행명 : ");
String bankName = scan.next();
System.out.print("예금주명 : ");
String bankUser = scan.next();
String sql = "insert into bankinfo (bank_no, bank_name, bank_user_name, bank_date)"
+ " values ('" + bankNo + "','" + bankName + "','" + bankUser + "',sysdate)";
// select문을 실행할 때는 executeQuery메서드를 사용하고,
// insert, update, delete문과 같이 select문이 아닌 쿼리문을 실행할 때는
// executeUpdate()메서드를 사용한다.
// executeUpdate()메서드의 반환값은 작업에 성공한 레코드 수를 반환한다.
int cnt = stmt.executeUpdate(sql);
System.out.println("반환값 : " + cnt);
if(cnt > 0) {
System.out.println("insert 성공~~~");
}else {
System.out.println("insert 실패!!!");
}
} catch (SQLException e) {
// TODO: handle exception
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
if(stmt!=null)try{stmt.close();}catch(SQLException e) {}
if(conn!=null)try{conn.close();}catch(SQLException e) {}
}
}
}