import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Dao {
private Connection conn = null;
private PreparedStatement pstmt = null;
private ResultSet rs = null;
public void insert(Vo vo) {
try {
// 1. JDBC 드라이버 (Oracle) 로딩
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2. Connection 얻어오기
String url = // "jdbc:oracle:thin:@localhost:1521:xe";
conn = DriverManager.getConnection(url, 이름, 비밀번호);
// 3. SQL문 준비 / 바인딩 / 실행
String query = "INSERT INTO 테이블 "
+ "VALUES (sequence.nextval, ?, ?, ?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, vo.getA());
pstmt.setString(2, vo.getB());
pstmt.setString(3, vo.getC());
int cnt = pstmt.executeUpdate();
System.out.println(cnt + "건 저장완료");
} catch (ClassNotFoundException e) {
System.out.println("error: 드라이버 로딩 실패 - " + e);
} catch (SQLException e) {
System.out.println("error:" + e);
} finally {
// 5. 자원정리
try {
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("error:" + e);
}
}
}
public List<Vo> getList() {
List<Vo> aList = new ArrayList<>();
Vo vo;
try {
// 1. JDBC 드라이버 (Oracle) 로딩
Class.forName("oracle.jdbc.driver.OracleDriver");
// 2. Connection 얻어오기
String url = // "jdbc:oracle:thin:@localhost:1521:xe";
conn = DriverManager.getConnection(url, 이름, 비밀번호);
// 3. SQL문 준비 / 바인딩 / 실행
String query = "SELECT no, A, B, C "
+ " FROM 테이블"
+ " ORDER BY no";
pstmt = conn.prepareStatement(query);
pstmt.executeQuery();
rs = pstmt.getResultSet();
while (rs.next()) {
vo = new UserVo();
vo.setNo(rs.getInt("no"));
vo.setA(rs.getString("A"));
vo.setB(rs.getString("B"));
vo.setC(rs.getString("C"));
aList.add(vo);
}
/* 결과 값 하나만 받을 때
rs = pstmt.executeQuery();
if(rs.next()){
vo.setA(rs.getInt("A"));
vo.setB(rs.getString("B"));
vo.setC(rs.getString("C"));
}
*/
} catch (ClassNotFoundException e) {
System.out.println("error: 드라이버 로딩 실패 - " + e);
} catch (SQLException e) {
System.out.println("error:" + e);
} finally {
// 5. 자원정리
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
System.out.println("error:" + e);
}
}
return aList;
}
}
'공부 > Java' 카테고리의 다른 글
JSTL 쓸 때 추가할 것 (0) | 2018.01.30 |
---|---|
spring 1 (0) | 2018.01.30 |
eclipse web.xml 만들기 (0) | 2018.01.23 |
JAVA MVC1, MVC2 정리 (0) | 2018.01.22 |
java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver (1) | 2018.01.22 |