반응형
1. DBConnection.java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection
{
public static Connection dbConn;
public static Connection getConnection()
{
Connection conn = null;
try {
String user = "scott";
String pw = "tiger";
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url, user, pw);
System.out.println("Database에 연결되었습니다.\n");
} catch (ClassNotFoundException cnfe) {
System.out.println("DB 드라이버 로딩 실패 :"+cnfe.toString());
} catch (SQLException sqle) {
System.out.println("DB 접속실패 : "+sqle.toString());
} catch (Exception e) {
System.out.println("Unkonwn error");
e.printStackTrace();
}
return conn;
}
}
2. DB 데이터추출 구현부
package DB;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class OracleTest
{
public static void main(String args[])
{
Connection conn = null; // DB연결된 상태(세션)을 담은 객체
PreparedStatement pstm = null; // SQL 문을 나타내는 객체
ResultSet rs = null; // 쿼리문을 날린것에 대한 반환값을 담을 객체
try {
// SQL 문장을 만들고 만약 문장이 질의어(SELECT문)라면
// 그 결과를 담을 ResulSet 객체를 준비한 후 실행시킨다.
String quary = "SELECT * FROM (select * from TEMP order by empno) where rownum<=10";
//String quary = "SELECT * FROM (select * from TEMP order by EMP_#) fetch first 100 rows only";
conn = DBConnection.getConnection();
pstm = conn.prepareStatement(quary);
rs = pstm.executeQuery();
System.out.println("EMPNO EMP_X KoreanName HanmunName CommonNumber");
System.out.println("============================================");
while(rs.next()){
String empno = rs.getString(1);
int emp_x = rs.getInt(2);
String Korean_name = rs.getString(3);
String Han_name = rs.getString(4);
int comm = rs.getInt("RES_#1");
//java.sql.Date hiredate = rs.getDate(5); // Date 타입 처리
String result = empno+" "+emp_x+" "+Korean_name+" "+Han_name+" "+comm;
// 직원번호 구분 한글이름 한문이름 주민번호
System.out.println(result);
}
} catch (SQLException sqle) {
System.out.println("SELECT문에서 예외 발생");
sqle.printStackTrace();
}finally{
// DB 연결을 종료한다.
try{
if ( rs != null ){rs.close();}
if ( pstm != null ){pstm.close();}
if ( conn != null ){conn.close(); }
}catch(Exception e){
throw new RuntimeException(e.getMessage());
}
}
}
}
반응형
'Programming > Java_Etc' 카테고리의 다른 글
AWT Study - 팝업메뉴 (0) | 2020.02.11 |
---|---|
AWT Study - 메뉴 생성 (0) | 2020.02.11 |
AWT Study - Window & Frame (0) | 2020.02.11 |
Java 막대 그래프 그리기2 (0) | 2020.02.08 |
Database Connection - DBConnection.java (0) | 2020.01.29 |