
package datos;

import encapsuladores.Libro;
import excepciones.GenericaExcepcion;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class LibrosDatos {   

public List<Libro> consultarTodos(Connection connection) throws Exception
{
    List<Libro> listaLibros = new ArrayList();
    ResultSet resultSet = null;
    Statement statement = null;
    try {
            String sql = "SELECT id_libro, titulo, generos.codigo, generos.descripcion, fecha_edicion, numero_paginas, premiado FROM generos INNER JOIN libros ON generos.codigo = libros.genero ORDER BY titulo";
            statement = connection.createStatement();
            resultSet = statement.executeQuery(sql);
            while (resultSet.next()) {
               Libro libro = new Libro();
               libro = new Libro();
               libro.setIdLibro(resultSet.getString(1));
               libro.setTitulo(resultSet.getString(2));
               libro.setGenero(resultSet.getString(3));
               libro.setDescripcion(resultSet.getString(4));
               libro.setFechaEdicion(resultSet.getDate(5));
               libro.setNumeroPaginas(resultSet.getInt(6));
               byte premiado = resultSet.getByte(7);                  
               if (premiado == 1)
                   libro.setPremiado(true);
               else
                   libro.setPremiado(false);                               
               listaLibros.add(libro);
            }
        } catch (SQLException excepcion) {
            throw new GenericaExcepcion(84);
        } finally
        {
            if (resultSet != null) resultSet.close(); 
            if (statement != null) statement.close();
        }
    return listaLibros;
}  


public Integer consultarNumeroFilas(Connection connection) throws Exception
{
    Integer numFilas = null;
    ResultSet resultSet = null;
    Statement statement = null; 
    String sql = "SELECT COUNT(*) FROM libros";

    try {
            statement = connection.createStatement(); 
            resultSet = statement.executeQuery(sql);
            if (resultSet.next()) {
               numFilas = new Integer(resultSet.getInt(1));          
            }   
        } catch (SQLException excepcion) {
            throw new GenericaExcepcion(85);
        } finally
        {
            if (resultSet != null) resultSet.close(); 
            if (statement != null) statement.close();
        }

    return numFilas;
}    
}
