728x90
Service
package com.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.ArrayList;
import com.dao.DAO;
import com.dto.DTO;
public class Service {
private String driver = "oracle.jdbc.driver.OracleDriver";
private String url = "jdbc:oracle:thin:@localhost:1521:xe";
private String user = "scott";
private String pass = "tiger";
private DAO dao;
public Service() {
dao = new DAO();
try {
Class.forName(driver);
System.out.println("드라이버 로딩 성공");
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("드라이버 로딩 실패");
}
}
public ArrayList<DTO> selectAll() {
ArrayList<DTO> list = null;
Connection con = null;
try {
con = DriverManager.getConnection(url, user, pass);
list = dao.selectAll(con);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
return list;
}
}
}
}
DAO
package com.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import com.dto.DTO;
public class DAO {
public ArrayList<DTO> selectAll(Connection con) {
ArrayList<DTO> list = new ArrayList<>();
PreparedStatement st = null;
ResultSet rs = null;
try {
String sql = "select empno, ename, job, mgr, to_char(hiredate, 'yyyy-mm-dd') hiredate, sal, comm, deptno from emp order by empno";
st = con.prepareStatement(sql);
rs = st.executeQuery();
while (rs.next()) {
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
String job = rs.getString("job");
int mgr = rs.getInt("mgr");
String hiredate = rs.getString("hiredate");
double sal = rs.getDouble("sal");
double comm = rs.getDouble("comm");
int deptno = rs.getInt("deptno");
DTO notice = new DTO(empno, ename, job, mgr, hiredate, sal, comm, deptno);
list.add(notice);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if(st!=null)st.close();
if(rs!=null)rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
}