package inukisoft.patronesj2ee.model.consulta.dao; import inukisoft.patronesj2ee.model.consulta.vo.ConsultaVO; import inukisoft.util.DateOperations; import inukisoft.util.exceptions.InternalErrorException; import inukisoft.util.sql.GeneralOperations; import java.sql.Connection; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.PreparedStatement; import java.sql.Timestamp; import java.util.Calendar; public class JDBC3CCSQLConsultaDAO extends AbstractSQLConsultaDAO { public ConsultaVO create(Connection connection, ConsultaVO vo) throws InternalErrorException { PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { // Crear sentencia SQL String queryString = "INSERT INTO Consulta" + " (consulta,fecha) VALUES (?,?)"; preparedStatement = connection.prepareStatement(queryString, Statement.RETURN_GENERATED_KEYS); // Completar SQL int i = 1; preparedStatement.setString(i++,vo.getConsulta()); Calendar fechaWithoutMilliSeconds = DateOperations.getDateWithoutMilliSeconds(vo.getFecha()); preparedStatement.setTimestamp(i++, new Timestamp( fechaWithoutMilliSeconds.getTime().getTime())); // Ejecutar SQL int insertedRows = preparedStatement.executeUpdate(); if (insertedRows == 0) { throw new SQLException("No puede agregar la fila a la tabla" + " 'Consulta'"); } if (insertedRows > 1) { throw new SQLException("fila duplicada en la tabla 'Consulta'"); } // Obtener el identificador de fila autonumerica (para drivers jdbc3cc resultSet = preparedStatement.getGeneratedKeys(); if (!resultSet.next()) { throw new InternalErrorException(new SQLException( "JDBC driver no retorno el identificador.")); } Long consultaIdentifier = new Long(resultSet.getLong(1)); // Retornar el VO con el identificador generado return new ConsultaVO(consultaIdentifier,vo.getConsulta(),vo.getFecha()); } catch (SQLException e) { throw new InternalErrorException(e); } finally { GeneralOperations.closeStatement(preparedStatement); } } }