package JDBC_Oracle;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
// 데이터 조회 프로그램
public class Oracle_SelectSample {
// 프로그램 전체 공유, 클래스 변수
private static int no;
private static String name;
private static String email;
private static String tel;
public static void main(String[] args) {
// 1. 드라이버 로딩
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String id = "java";
String password = "1234";
// 2. Connection
try {
Class.forName(driver);
} catch (ClassNotFoundException e1) {
e1.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(url, id, password);
} catch (SQLException e1) {
System.out.println("DB 접속이 실패했습니다. URL : " + url + "\tID : " + id + "\tPW : " + password);
e1.printStackTrace();
}
// 3. SQL 실행
String sql = "select * from member";
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
} catch (SQLException e1) {
e1.printStackTrace();
}
ResultSet rs = null;
try {
rs = pstmt.executeQuery();
} catch (SQLException e1) {
e1.printStackTrace();
}
// 4. 조회, 삭제, 수정, 입력
System.out.println("--------------------------------------------------------");
System.out.println("번호 \t 이름 \t 이메일 \t 전화번호");
System.out.println("--------------------------------------------------------");
try {
while(rs.next()) {
no = rs.getInt("no");
name = rs.getString("name");
email = rs.getString("email");
tel = rs.getString("tel");
System.out.println(no + "\t" + name + "\t" + email + "\t" + tel);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("--------------------------------------------------------");
// 5. Connection 해제
// Connection 연결과 반대로 진행
try {
if(rs != null) {
rs.close();
}
if(pstmt != null) {
pstmt.close();
}
if(conn != null) {
conn.close();
}
} catch(Exception e) {
System.out.println("Unknown error happens");
}
}
}