class StudentDAO extends AbstractDAO <Integer, Student> {
private static final String SQL_SELECT_ALL_STUDENT = "SELECT ID, FIRST_NAME, SECOND_NAME, BIRTH_DATE,ENTER_YEAR FROM STUDENT";
private static final String SQL_SELECT_STUDENT_BY_ID = "SELECT FIRST_NAME, SECOND_NAME, BIRTH_DATE,ENTER_YEAR FROM STUDENT WHERE ID=?";
private static final String SQL_SELECT_STUDENT_BY_LASTNAME ="SELECT id,FIRST_NAME,BIRTH_DATE,ENTER_YEAR FROM. STUDENT WHERE SECOND_NAME=?";
private static final String SQL_DELETE_STUDENT_BY_ID = "DELETE FROM STUDENT WHERE ID =?";
private static final String SQL_INSERT_STUDENT = "INSERT INTO STUDENT"+"(FIRST_NAME, SECOND_NAME, BIRTH_DATE, ENTER_YEAR)"+"VALUES (?,?,?,?)";
private PreparedStatement preparedStatement1;
private PreparedStatement preparedStatementSelectById;
private PreparedStatement preparedStatementfindAll;
private PreparedStatement preparedStatementDeleteStudentById;
private PreparedStatement preparedStatementInsertStudent;
public StudentDAO(Connection connection) throws DAOException, SQLException {
super(connection);
try {
preparedStatementInsertStudent =connection.prepareStatement(SQL_INSERT_STUDENT);
preparedStatement1 = connection.prepareStatement(SQL_SELECT_STUDENT_BY_LASTNAME);
preparedStatementfindAll = connection.prepareStatement(SQL_SELECT_ALL_STUDENT);
preparedStatementDeleteStudentById = connection.prepareStatement(SQL_DELETE_STUDENT_BY_ID);
preparedStatementSelectById = connection.prepareStatement(SQL_SELECT_STUDENT_BY_ID);
} catch (Exception e) {
throw new DAOException(e);
}
}
代码示例越高,如果在类的设计者中使用ps,就会出现如何关闭ps的困难。
答案 0 :(得分:1)
所以我假设您将拥有使用语句的方法。喜欢:
public void executepreparedStatementInsertStudent (Connection connection){
PreparedStatement preparedStatementInsertStudent =connection.prepareStatement(SQL_INSERT_STUDENT);
// create statement
// execute query
// close statement
}
public void executePreparedStatementDeleteStudentById (Connection connection){
PreparedStatement preparedStatementDeleteStudentById = connection.prepareStatement(SQL_DELETE_STUDENT_BY_ID);
// create statement
// execute query
// close statement
}
.... 等等
<强>更新强>
当规范多次重新使用时,我认为它们的意思是:
PreparedStatement ps = connection.prepare("SQL_DELETE_STUDENT_BY_ID");
for (Student student : students) {
ps.setInt(1, student.getId());
ps.executeUpdate();
}
ps.close();
并且在完成后仍然关闭它,并且不要保持资源打开。