select 쿼리

select 쿼리는 executeQuery() 메소드를 이용한다.
executeQuery() 메소드는 ResultSet으로 리턴되며
ResultSet의 next() 등을 이용하여 결과를 보여주게된다.


package step3;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import config.DbConfig;

public class TestJdbc3 {
 public static void main(String[] args) {
 Connection con = null;
 Statement stmt = null;
 ResultSet rs = null;    // select 조회 결과를 열어볼 수 있도록 추상메서드를 제공..

 try {
 Class.forName(DbConfig.driver);
 System.out.println("1. Driver Loading...");

 con = DriverManager.getConnection(DbConfig.url, DbConfig.user, DbConfig.pass);
 System.out.println("2. Connection...");

 stmt = con.createStatement();
 System.out.println("3. Statement...");

 String sql = "select id, password, name, address from member";
 // Select 문은 executeQuery() 메소드를 이용한다
 rs = stmt.executeQuery(sql);    // ResultSet 으로 리턴되어짐

 // next() : 다음 행이 존재하면 true 아니면 false
 while(rs.next()){
 String id = rs.getString(1);
 String password = rs.getString(2);
 String name = rs.getString(3);
 String address = rs.getString("address");    // 컬러명으로도 가능하다.
 System.out.println("id : " + id + ", password : " + password +
 ", name : " + name + ", address : " + address);
 }// whiles
 System.out.println("4. Query 실행...");

 } catch (ClassNotFoundException e) {
 e.printStackTrace();
 } catch (SQLException e) {
 e.printStackTrace();
 } finally {
 if(rs != null){
 try {
 rs.close();
 System.out.println("rs.close()");
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }// if
 if(stmt != null){
 try {
 stmt.close();
 System.out.println("stmt.close()");
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }// if
 if(con != null){
 try {
 con.close();
 System.out.println("con.close()");
 } catch (SQLException e) {
 e.printStackTrace();
 }
 }// if
 System.out.println("5. Close...");
 }// finally

 }// main
}// class
Comment are closed.