본문 바로가기

JAVA/JDBC

JDBC : preparedStatement(select) 실습

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import java.sql.Statement;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.SQLException;

//jdbc : preparedStatement(select) 실습

 

public class jdbcEx04 {

        public static void main(String[] args) {

              

               Connection conn = null;

               PreparedStatement pstmt = null;      

               ResultSet rs = null;

              

               try {

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

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

                      

                       String query = "select * from emp where deptno=?";

                       pstmt = conn.prepareStatement(query);

                      

                       pstmt.setInt(1, 30);

                       rs = pstmt.executeQuery();

                      

                       while(rs.next()){     

                              String empno = rs.getString("empno");

                              String ename = rs.getString("ename");

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

                             

                             

                          System.out.println(empno + "\t" + ename +  "\t" + deptno + "\t");

                       }

                      

                      

               } catch (ClassNotFoundException e) {

                       e.printStackTrace();

               } catch (SQLException e) {

                       e.printStackTrace();

               } finally{

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

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

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

               }

 

        }

}

 

 

 

 

출력물

7499 ALLEN 30 
7521 WARD 30 
7654 MARTIN 30 
7698 BLAKE 30 
7844 TURNER 30 
7900 JAMES 30