Oracle JDBC,  날짜에 시간 포함하여 DB에 입출력하기


오라클의 DATE 형 컬럼에 java.sql.Date 형 오브젝트를 저장할 때

pstmt.setDate(1, hiredate);

오라클로부터 java.sql.Date 형으로 가져오기

java.sql.Date hiredate = rs.getDate("HIREDATE");


오라클의 DATE 형 컬럼에 날짜와 시분초까지 저장하고 가져오기( java.sql.Timestamp )

pstmt.setTimestamp(1, new java.sql.Timestamp( uDate.getTime() ) );

java.sql.Timestamp hiredate = rs.getTimestamp("HIREDATE");


	public boolean insertDate(){
		String sql = "INSERT INTO emp2 (empno, ename, hiredate) VALUES(?,?,?)";
		conn = getConn();
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setInt(1, 1234);
			pstmt.setString(2, "김인철");
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			java.sql.Timestamp hiredate = null;
			try {
				java.util.Date uDate = dateFormat.parse("2016-12-05 06:11:03");
				hiredate = new Timestamp(uDate.getTime());
			} catch (ParseException e) {
				e.printStackTrace();
			}
			pstmt.setTimestamp(3, hiredate);
			int n = pstmt.executeUpdate();
			return n>0 ? true : false;
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			closeAll();
		}
		return false;
	}
	
	public java.sql.Timestamp getHiredate() {
		String sql = "SELECT empno, ename, hiredate FROM emp2 WHERE empno=1234";
		conn = getConn();
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next()){
				int empno = rs.getInt("EMPNO");
				String ename = rs.getString("ENAME");
				java.sql.Timestamp hiredate = rs.getTimestamp("HIREDATE");
				return hiredate;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally{
			closeAll();
		}
		return null;
	}
	public static void main(String[] args){
		java.sql.Timestamp hiredate = new EmpDAO().getHiredate();
		System.out.println("가공전:"+hiredate);
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(hiredate.getTime());
		System.out.printf("년:%d 월:%d 일:%d 시:%d 분:%d 초:%d 밀리초:%d %n",
				cal.get(Calendar.YEAR),
				cal.get(Calendar.MONTH),
				cal.get(Calendar.DAY_OF_MONTH),
				cal.get(Calendar.HOUR_OF_DAY),
				cal.get(Calendar.MINUTE),
				cal.get(Calendar.SECOND),
				cal.get(Calendar.MILLISECOND)
				);
		
	}


저작자 표시
신고
Posted by cwisky