-
[JDBC] select, insert, update, deleteDataBase/JDBC 2022. 9. 9. 15:47
select(조회)
next()
-최초 실행은 객체의 시작부분(데이터 없는곳)에서 첫번재 레코드로 이동하는 메서드.
-그 다음 실행부터는 다음 레코드로 이동하는 명령이 됨.
-이동하며 레코드를 rs라는 이름으로 액세스 함.
getInt()
-number형 필드값을 추출하는 메서드.
-괄호 안에 필드이름을 정확히 써야함(필드명에 오타가 있거나 안 맞으면 부적합한 열이름 이라는 에러가 발생함)
getString()
-varchar2형(문자형) 필드값을 추출하는 메서드
-모든 자료형에 대해 get~() 메서드가 모두 존재함
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JDBC_Select { public static void main(String[] args) { String driver="oracle.jdbc.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:xe"; String id="scott"; String pw= "tiger"; Connection con=null; PreparedStatement pstmt=null; // con에 연결하여 SQL 명령을 실행해주는 객체 ResultSet rs=null; // SQL(select) 실행결과를 저장하는 객체 // 한개의 클래스 실행에서 한개의 SQL을 실행하고 그 결과를 처리함 // 아래는 그 한개의 SQL문을 String 변수에 저장하여 사용하는 예 String sql="select*from customer"; // 데이터베이스 연결 후 // SQL 명령을 사용하기 위해 String 변수에 SQL 명령을 준비함 // 데이터베이스에 제공되어질 명령이므로 String형으로 준비함 try { Class.forName(driver); con=DriverManager.getConnection(url, id, pw); // SQL문을 장착한 con을 pstmt에 전달함 pstmt=con.prepareStatement(sql); // pstmt=con.prepareStatement(select*from customer); // pstmt에 담겨진 SQL 명령을 실행하고 // 그 결과를 rs에 저장함 rs=pstmt.executeQuery(); // rs에 저장된 데이터는 첫번째 레코드단위로, // 두번째 얻어준 레코드에서 다시 필드단위로 꺼내어 씀 // 다만 맨처음 레코드를 얻어오기 위해서 // 현재 포커스인 데이터의 시작 부분에서 // 첫번째 레코드로 이동해야하므로 // rs.next()라는 명령으로 이동하고 포커스를 맞춤 System.out.println("번호 \t 이름 \t\t 이메일 \t\t\t 전화번호"); System.out.println("---------------------------------------------------------"); // while(true)에 true 대신 rs.next()를 넣어 코드 축약 while(rs.next()) { int num=rs.getInt("num"); String name=rs.getString("name"); String email=rs.getString("email"); String tel=rs.getString("tel"); System.out.printf("%d \t %s \t %s \t %s\n",num,name,email,tel); // boolean a=rs.next(); // while(true) 시 필요 코드 // if(a==false) break; // while(true) 시 필요 코드 } // 1. pstmt에 sql을 장착하고 실행해서 그 결과를 rs에 저장함 // 2. 저장결과를 하나씩 레코드별로 필드별로 하나씩 꺼내서 콘솔창에 출력함 } catch (ClassNotFoundException e) {e.printStackTrace(); } catch (SQLException e) {e.printStackTrace(); } try { if(con!=null) con.close(); if(pstmt!=null) pstmt.close(); if(rs!=null) rs.close(); } catch (SQLException e) {e.printStackTrace(); } } }
실행 결과
insert(추가)
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class JDBC_Insert { public static void main(String[] args) { String driver="oracle.jdbc.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:xe"; String id="scott"; String pw= "tiger"; Connection con=null; PreparedStatement pstmt=null; // insert 명령의 경우 결과값이 따로 없어서 ResultSet은 사용하지 않음 try { Class.forName(driver); con=DriverManager.getConnection(url, id, pw); Scanner sc=new Scanner(System.in); System.out.print("이름: "); String name=sc.nextLine(); System.out.print("이메일: "); String email=sc.nextLine(); System.out.print("전화번호: "); String tel=sc.nextLine(); // 방법 1. 모든 입력값을 수동으로 임의 설정한 예 // String sql="insert into customer values(6,'김하나',abc5@naver.com','010-1111-2222')"; // 방법 2. 시쿼스를 이용한 예 // String sql="insert into customer values(num_seq.nextVal,'김하나',abc5@naver.com','010-1111-2222')"; // 방법 3. 변수값을 sql문에 같이 삽입하는 옛날 방식 // String sql="insert into customer values(num_seq.nextVal,'"+name+"','"+email+"','"+tel+"')"; // 방법 4. 요즘 방식(물음표 이용) String sql="insert into customer values(num_seq.nextVal, ?, ?, ?)"; pstmt=con.prepareStatement(sql); // ?의 순서에 맞춰서 변수에 저장된 값들을 각 물음표에 맞춰서 매칭시킴 pstmt.setString(1, name); pstmt.setString(2, email); pstmt.setString(3, tel); // 사용하는 변수값과 필드 자료가 정수형이라면 setInt() 메서드를 사용함. 그외 자료도 자료에 맞게 사용. // SQL select 명령만 excuteQuery를 사용하고 나머지는 excuteUqdate 메서드를 사용. int result=pstmt.executeUpdate(); // excuteUpdate의 결과를 sql 명령이 정상 동작했을 때 1, 실패했을 때 0이 리턴됨 if(result==1) System.out.println("레코드 추가 성공"); else System.out.println("레코드 추가 실패"); } catch (ClassNotFoundException e) {e.printStackTrace(); } catch (SQLException e) {e.printStackTrace(); } try { if(con!=null) con.close(); if(pstmt!=null) pstmt.close(); } catch (SQLException e) {e.printStackTrace(); } } }
update(수정)
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class JDBC_Update { public static void main(String[] args) { String driver="oracle.jdbc.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:xe"; String id="scott"; String pw= "tiger"; Connection con=null; PreparedStatement pstmt=null; try { Class.forName(driver); con=DriverManager.getConnection(url, id, pw); Scanner sc=new Scanner(System.in); System.out.print("수정할 회원 번호: "); String num=sc.nextLine(); System.out.print("수정할 항목 선택(1:성명 2:이메일 3:전화번호) "); String input=sc.nextLine(); String sql=""; switch(input) { case "1": System.out.printf("수정할 이름: "); String name=sc.nextLine(); sql="update customer set name=? where num=?"; pstmt=con.prepareStatement(sql); pstmt.setString(1, name); pstmt.setInt(2, Integer.parseInt(num)); break; case "2": System.out.printf("수정할 이메일: "); String email=sc.nextLine(); sql="update customer set email=? where num=?"; pstmt=con.prepareStatement(sql); pstmt.setString(1, email); pstmt.setInt(2, Integer.parseInt(num)); break; case "3": System.out.printf("수정할 전화번호: "); String tel=sc.nextLine(); sql="update customer set tel=? where num=?"; pstmt=con.prepareStatement(sql); pstmt.setString(1, tel); pstmt.setInt(2, Integer.parseInt(num)); break; } int result=pstmt.executeUpdate(); if(result==1) System.out.println("수정 성공"); else System.out.println("수정 실패"); } catch (ClassNotFoundException e) {e.printStackTrace(); } catch (SQLException e) {e.printStackTrace(); } try { if(con!=null) con.close(); if(pstmt!=null) pstmt.close(); } catch (SQLException e) {e.printStackTrace(); } } }
delete(삭제)
import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Scanner; public class JDBC_Delete { public static void main(String[] args) { String driver="oracle.jdbc.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:xe"; String id="scott"; String pw= "tiger"; Connection con=null; PreparedStatement pstmt=null; try { Class.forName(driver); con=DriverManager.getConnection(url, id, pw); Scanner sc=new Scanner(System.in); // 삭제할 레코드의 번호를 입력받음 System.out.print("삭제할 레코드 번호: "); String num=sc.nextLine(); // sql문을 작성 저장 String sql="delete from customer where num=?"; // pstmt에 장착 pstmt=con.prepareStatement(sql); pstmt.setInt(1, Integer.parseInt(num)); // sql문 실행 int result=pstmt.executeUpdate(); // 실행결과 -> 삭제 성공 또는 삭제 실패로 출력 if(result==1) System.out.println("삭제 성공"); else System.out.println("삭제 실패"); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } try { if(con!=null) con.close(); if(pstmt!=null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } }
번호 6에 해당하는 레코드가 삭제됨 'DataBase > JDBC' 카테고리의 다른 글
[JDBC] singleton (0) 2022.09.09 [JDBC] DTO, DAO (0) 2022.09.09 [JDBC] 연습하기 (0) 2022.09.09 [JDBC] Java Database Connectivity (0) 2022.09.09