public void createStudent(Student student) { Connection conn = null; try { conn = getDatabaseConnection(); String sql = "INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(?,?,?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1, student.getStudId()); pstmt.setString(2, student.getName()); pstmt.setString(3, student.getEmail()); pstmt.setDate(4, new java.sql.Date(student.getDob().getTime())); pstmt.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e); } finally { if(conn!= null){ try { conn.close(); } catch (SQLException e){ } } } }
public Student createStudent(Student student) { Address address = student.getAddress(); if(address != null){ addressMapper.insertAddress(address); } if(student.getName()==null || student.getName().trim().length()==0){ throw new RuntimeException("Student Name should not be null"); } studentMapper.insertStudent(student); return student; }
public static void main(String[] args) { JdbcStudentService service = new JdbcStudentService(); Student existingStudent = service.findStudentById(1); System.out.println(existingStudent); long ts = System.currentTimeMillis();//For creating unique student names Student newStudent = new Student(0,"student_"+ts,"student_"+ts+"@gmail.com",new Date()); service.createStudent(newStudent); System.out.println(newStudent); int updateStudId = 3; Student updateStudent = service.findStudentById(updateStudId); ts = System.currentTimeMillis();//For creating unique student email updateStudent.setEmail("student_"+ts+"@gmail.com"); service.updateStudent(updateStudent); }
public void updateStudent(Student student) { Connection conn = null; try { conn = getDatabaseConnection(); conn = getDatabaseConnection(); String sql = "UPDATE STUDENTS SET NAME=?,EMAIL=?,DOB=? WHERE STUD_ID=?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, student.getName()); pstmt.setString(2, student.getEmail()); pstmt.setDate(3, new java.sql.Date(student.getDob().getTime())); pstmt.setInt(4, student.getStudId()); pstmt.executeUpdate(); } catch (SQLException e) { throw new RuntimeException(e.getCause()); } finally { if(conn!= null){ try { conn.close(); } catch (SQLException e){ } } } }