본문 바로가기

JAVA/JDBC

JDBC : Statement (select 실습)

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

//jdbc : select 실습

 

public class jdbcEx03 {

        public static void main(String[] args) {

              

               Connection conn = null;

               Statement stmt = null;

              

               //select 리턴값을 자바객체로 표현

               ResultSet rs = null;

              

               try {

                       Class.forName("oracle.jdbc.driver.OracleDriver");

                       conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");

                      

                       stmt = conn.createStatement();

 

//                     select 구문 실습

                   String query = "select deptno no, dname name, loc location from dept2";

                      

                      

                       rs = stmt.executeQuery(query);

                      

//                     select 값이 없을때까지 반복

                       while(rs.next()){     

//                            String deptno = rs.getString("deptno");

//                            String dname = rs.getString("dname");

//                            String loc = rs.getString("loc");

                             

                              String deptno = rs.getString(1);

                              String dname = rs.getString(2);

                              String loc = rs.getString(3);

                             

                           System.out.println(deptno + "\t" + dname +  "\t" + loc + "\t");

                       }

                      

                       int count = stmt.executeUpdate(query);

                      

                       System.out.println("영향받은 행수 : " + count);

                      

               } catch (ClassNotFoundException e) {

                       e.printStackTrace();

               } catch (SQLException e) {

                       e.printStackTrace();

               } finally{

                       if(stmt != null) try{ stmt.close();} catch(SQLException e){};

                       //신형버젼에선 auto commit 해주지만 구형버젼에선 close 해줘야 commit

                      

                       if(rs != null) try{ rs.close();} catch(SQLException e){};

                       if(conn != null) try{ conn.close();} catch(SQLException e){};

               }

 

        }

}

 

 

 

 

출력물

10 ACCOUNTING NEW YORK 
20 RESEARCH DALLAS 
30 SALES CHICAGO 
40 OPERATIONS BOSTON 
50 총무부 서울 
영향받은 행수 : 5

'JAVA > JDBC' 카테고리의 다른 글

JDBC : preparedStatement(insert) 실습  (0) 2013.02.26
JDBC : preparedStatement(select) 실습  (0) 2013.02.26
JDBC : DML(insert, update, Delete), DDL(crate table) 실습  (0) 2013.02.26
JDBC : 오라클 접속 실습  (0) 2013.02.26
ResultSet 이란??  (0) 2013.02.25