ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • java :: jdbc-2
    IT/Java & JSP & FW 2011. 12. 30. 11:52
    Statement 객체 (정적)
    statement 객체는 statement 인터페이스를 구현한 객체로 실제 SQL문을 수행하기 위해서 사용하며 항상 인수가 없는 Connection 클래스의 createStatement()메소드를 호출함으로써 얻어진다.

    형식

    Statement stmt=conn.createStatement();

     
    SQL문을 전송메소드들
    select문
    ResultSet re=stmt.executeQuery('select문');
    ResultSet 에 관해 조사해 볼 것.

    insert문
    update문
    delete문 
    int count=st.executeUpdate('구문');

    예제1
    (MyJdbc.java)
    import java.sql.*;
    
    public class MyJdbc {
    
    	public static void main(String[] args) {
    		try{
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    			System.out.println("드라이버 성공");
    			
    			String url="";
    			String user="";
    			String pwd="";
    			Connection conn=
    					DriverManager.getConnection(url, user, pwd);
    			
    			//statement는 인터페이스임으로 new로 만들 수 없다.
    			Statement st=conn.createStatement();
    			String str="insert into student1 values('오미자',18,'서울','02-222-1111')";  //DB에 값 삽입하기 위해 String 객체 생성 후 DB에 넘겨서 행을 실행
    			int count=st.executeUpdate(str);  //윗 줄을 실행하면 int형의 반환된 값이 나옴
    			System.out.println(count+"행이 실행됨");  //반환된 int 값을 출력함으로써 작업이 잘 이루어 졌는지 확인함.
    			
    			conn.close();
    			
    		}catch(ClassNotFoundException e){
    			System.out.println("드라이버 없음");
    		}catch(SQLException e){
    			System.out.println("디비연결 오류");
    		}
    		
    	}
    
    }
    

    예제2
    (MyJdbc2.java) 
    import java.sql.*;
    
    
    public class MyJdbc2 {
    
    	public static void main(String[] args) {
    		
    		try{
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    			System.out.println("드라이버 연결 성공");
    			
    			String url="";
    			String user="";
    			String pass="";
    			
    			Connection conn=
    					DriverManager.getConnection(url, user, pass);
    			System.out.println("DB연결 성공");
    			
    			Statement st=conn.createStatement();
    			String str="delete from student1 where name='둘리'";
    			int count=st.executeUpdate(str);
    			System.out.println(count+" 행이 실행됨.");
    			
    			conn.close();
    						
    		}catch(ClassNotFoundException e){
    			System.out.println("드라이버 못찻음");
    		}catch(SQLException e){
    			System.out.println("디비 연결 오류");
    		}
    	}
    
    }
    


     
    PreparedStatement 객체(동적)
    SQL문이 이미 가진 Statement가 DB에 넘겨져 컴파일 되어지고 sql문의 ?(in파라미터)만 나중에 추가해 실행되는 준비된 statement 객체

    장점
    반복적인 sql문을 실행할 때 실행이 더 빠르다

    단점
    sql 문마다 PrepareStatement 객체를 생성해야 한다
    (재사용 불가능) 

    형식

    String sql="insert into menber value(?,?,?,?)"
    PreparedStatement patmt=con.

    prepareStatement(sql);

    pstmt.set[xxx](파라미터순서, 실제데이터) 

     
    예제1
    (MyJdbc3.java) 
    import java.sql.*;
    
    public class MyJdbc3 {
    
    	public static void main(String[] args) {
    
    		try{
    			
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    			System.out.println("드라이버 로드 완료");
    			
    			String url="";
    			String user="";
    			String pass="";
    			
    			Connection conn=
    					DriverManager.getConnection(url,user,pass);
    			
    			
    			String sql="insert into student1 values(?,?,?,?)";  //SQL에 이미 셋팅을 해둔다.
    			PreparedStatement ps=conn.prepareStatement(sql);  //윗줄을 항상 가지고 있게끔 객체를 생성해준다.
    			
    			ps.setString(1, "레스비");  //첫 번째 ? 에 레스비를 넣는다. 
    			ps.setInt(2, 40);
    			ps.setString(3, "부천");
    			ps.setString(4, "031-333-3333");
    			
    			int count=ps.executeUpdate();  //실행이 바로 되고 결과값을 받는다.
    			System.out.println(count+"행이 삽입됨");
    		
    			ps.close();
    			conn.close();  
    			
    		}catch(ClassNotFoundException e){
    			
    		}catch(SQLException e){
    			
    		}
    	}
    
    }
    

    예제2
    (MyJdbc4.java) 
    import java.sql.*;
    import java.io.*;
    
    public class MyJdbc4 {
    
    	public static void main(String[] args) throws IOException {
    		
    		BufferedReader in=
    				new BufferedReader(new InputStreamReader(System.in));
    		
    		
    		try{
    			Class.forName("oracle.jdbc.driver.OracleDriver");
    			System.out.println("드라이버 연결 성공");
    			
    			String url="";
    			String user="";
    			String pass="";
    			
    			Connection conn=
    					DriverManager.getConnection(url, user, pass);
    			
    			System.out.println("검색할 학생의 이름을 입력해주세요!");
    			String str=in.readLine();
    			
    			String sql="select * from student1 where name=?";
    			PreparedStatement ps=conn.prepareStatement(sql);
    			ps.setString(1, str);
    			ResultSet rs=ps.executeQuery();
    			
    			if(rs.next()){
    				String name=rs.getString(1);
    				int age=rs.getInt(2);
    				String addr=rs.getString(3);
    				String tel=rs.getString(3);
    				System.out.println(name+"\t"+age+"\t"+addr+"\t"+tel);
    			}else{
    				System.out.println("등록된 학생이 없습니다.");
    			}
    				
    			rs.close();
    			ps.close();
    			conn.close();
    			
    		}catch(ClassNotFoundException e){
    			System.out.println("드라이버를 못 찼음");
    		}catch(SQLException e){
    			System.out.println("DB연결 오류");
    		}
    			
    		
    	}
    }

    'IT > Java & JSP & FW' 카테고리의 다른 글

    java :: 형변환 (캐스팅, casting)  (0) 2012.02.29
    java :: 접근제어자  (0) 2012.02.28
    java :: JDBC 연동, SQL 연동 및 SQL 기초 설명  (0) 2011.12.29
    java :: GUI 프로그래밍-3  (0) 2011.12.28
    java :: GUI 프로그래밍-2  (0) 2011.12.27
Designed by Tistory.