JDBC Programming
SimpleJDBC.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SimpleJDBC {
public static void main(String[] args) {
//1. 드라이버 로드
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println("드라이버로드 성공");
} catch (ClassNotFoundException e) {
System.out.println("드라이버클래스를 찾을 수 없습니다.");
}
//2. 커넥션 생성
Connection con = null;
try {
String URL = "jdbc:oracle:thin:@localhost:1521/xe";
String ID = "hr";
String PW = "hr";
con = DriverManager.getConnection(URL, ID, PW);
System.out.println(con);
//3. SQL 구문 작성
String sql = "select first_name, salary from employees where employee_id=103";
//4. Statement 객체 생성
PreparedStatement stmt = con.prepareStatement(sql);
//5. 쿼리문 실행
ResultSet rs = stmt.executeQuery();
//6. 결과집합 소비
if(rs.next()) {
String name = rs.getString("first_name");
int salary = rs.getInt("salary");
System.out.println(name + ", " + salary);
}else {
System.out.println("조회한 데이터가 없습니다.");
}
}catch(SQLException e) {
System.out.println(e.getMessage());
}finally {
//7. 커넥션 닫기
if(con!=null) {
try { con.close(); } catch(Exception e) {}
}
}
}//end main
}//end class
|