Java - Como leer datos de una base de datos

 
Vista:
sin imagen de perfil
Val: 32
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Como leer datos de una base de datos

Publicado por Juan (18 intervenciones) el 14/08/2018 17:45:29
Buenas tardes tengo que leer los datos de una base de datos y tengo un problema.
Tengo tres clases llamadas Cliente, Artículos y Alquiler. Cuando quiero recuperar los datos de la base de datos no se como puedo recuperar los datos que están en la clase Articulo.
He probado con : objAlquiler.setArticulo(objArticulo.setIdentificador(rs.getInt(1)));
pero me da error.
Me puede ayudar alguien?.
Muchas Gracias.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
public class Cliente {
 
 
    private String nif;
    private String nombre;
    private String apellidos;
    private Date nacimiento;
 
    public String getNif() {
        return nif;
    }
 
    public void setNif(String nif) {
        this.nif = nif;
    }
 
    public String getNombre() {
        return nombre;
    }
 
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
 
    public String getApellidos() {
        return apellidos;
    }
 
    public void setApellidos(String apellidos) {
        this.apellidos = apellidos;
    }
 
    public Date getNacimiento() {
        return nacimiento;
    }
 
    public void setNacimiento(Date nacimiento) {
        this.nacimiento = nacimiento;
    }
 
    public Cliente(String nif, String nombre, String apellidos, Date nacimiento) {
        this.nif = nif;
        this.nombre = nombre;
        this.apellidos = apellidos;
        this.nacimiento = nacimiento;
    }
 
    public Cliente(){
 
    }
 
}
 
public class Articulo {
 
    private int identificador;
    private String nombre;
    private boolean mas18;
    private boolean alquilado;
 
//    public Articulo() {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
//    }
 
    public int getIdentificador() {
        return identificador;
    }
 
    public void setIdentificador(int identificador) {
        this.identificador = identificador;
    }
 
    public String getNombre() {
        return nombre;
    }
 
    public void setNombre(String nombre) {
        this.nombre = nombre;
    }
 
    public boolean isMas18() {
        return mas18;
    }
 
    public void setMas18(boolean mas18) {
        this.mas18 = mas18;
    }
 
    public boolean isAlquilado() {
        return alquilado;
    }
 
    public void setAlquilado(boolean alquilado) {
        this.alquilado = alquilado;
    }
 
    public Articulo(int identificador, String nombre, boolean mas18, boolean alquilado) {
        this.identificador = identificador;
        this.nombre = nombre;
        this.mas18 = mas18;
        this.alquilado = alquilado;
    }
 
    public Articulo(){
 
    }
 
}
 
public class Alquiler {
 
    private Cliente cliente;
    private Articulo articulo;
    private Date fecha;
 
    public Cliente getCliente() {
        return cliente;
    }
 
    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }
 
    public Articulo getArticulo() {
        return articulo;
    }
 
    public void setArticulo(Articulo articulo) {
        this.articulo = articulo;
    }
 
    public Date getFecha() {
        return fecha;
    }
 
    public void setFecha(Date fecha) {
        this.fecha = fecha;
    }
 
    public Alquiler(Cliente cliente, Articulo articulo, Date fecha) {
        this.cliente = cliente;
        this.articulo = articulo;
        this.fecha = fecha;
    }
 
    public Alquiler(){
 
    }
 
}
 
public static HashMap<String, Alquiler> filtrarAlquileres(int tipoFiltro, String valor) throws Exception{
    DataSource data = null;
    ResultSet rs = null;
    PreparedStatement st;
    st = null;
 
    HashMap<String, Alquiler> hashAlquileres = new HashMap<String, Alquiler>();
 
    try {
        data = new DataSource();
        st = data.getStatement("SELECT NIF,IDENTIFICADOR,FECHA FROM ALQUILER WHERE NIF = ?");
        st.setString(1, valor);
        rs = data.ejecutarSelect(st);
        while (rs.next()) {
            Alquiler objAlquiler = new Alquiler();
            Articulo objArticulo = new Articulo();
            objAlquiler.setArticulo(objArticulo.setIdentificador(rs.getInt(1)));
            objAlquiler.setFecha(rs.getDate(4));
            hashAlquileres.put(objAlquiler.getCliente().getNif(), objAlquiler);
 
        }
        rs.close();
        return hashAlquileres;
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
        throw new Exception(ex.getMessage());
    } finally {
        if (rs != null) rs.close();
        if (st != null) st.close();
        if (data != null) data.cerrarConexion();
    }
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de kingk
Val: 247
Ha mantenido su posición en Java (en relación al último mes)
Gráfica de Java

Como leer datos de una base de datos

Publicado por kingk (108 intervenciones) el 14/08/2018 23:51:49
Hola, la linea te da error porque le pasas al metodo setArticulo el metodo setIdentificador de la clase articulo que no devuelve nada, lo que supongo intentas es asignar el identificador al Articulo del objeto Alquiler que creas para lo cual tendrias que hacerlo asi:
1
objAlquiler.getArticulo().setIdentificador(rs.getInt(1));
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
1
Comentar
sin imagen de perfil
Val: 32
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Como leer datos de una base de datos

Publicado por Juan (18 intervenciones) el 15/08/2018 09:56:04
Muchas gracias Kigk.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 32
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Como leer datos de una base de datos

Publicado por Juan (18 intervenciones) el 16/08/2018 16:46:02
Buenas tardes Kingk, he hecho lo que me dijiste pero sigue sin funcionar. En cuanto ejecuta esta sentencia: objAlquiler.getArticulo().setIdentificador(rs.getInt(4)); se va directamente al finally.
te pongo la función mas abajo.

Muchas Gracias.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
public static HashMap<String, Alquiler> filtrarTodosAlquileres() throws Exception {
    DataSource data = null;
    ResultSet rs = null;
    PreparedStatement st;
    st = null;
 
    HashMap<String, Alquiler> hashAlquileres = new HashMap<String, Alquiler>();
 
    try {
        data = new DataSource();
        st = data.getStatement(QUERY);
        rs = data.ejecutarSelect(st);
        while (rs.next()) {
            Alquiler objAlquiler = new Alquiler();
            objAlquiler.getArticulo().setIdentificador(rs.getInt(4));
            //Despues de ejecutar la sentencia anterior se va directamente al finally.
            objAlquiler.getArticulo().setNombre(rs.getString(5));
            objAlquiler.getArticulo().setMas18(rs.getBoolean(6));
            objAlquiler.getArticulo().setAlquilado(rs.getBoolean(7));
            objAlquiler.getCliente().setNif(rs.getString(8));
            objAlquiler.getCliente().setNombre(rs.getString(9));
            objAlquiler.getCliente().setApellidos(rs.getString(10));
            objAlquiler.getCliente().setNacimiento(rs.getDate(11));
            objAlquiler.setFecha(rs.getDate(3));
            hashAlquileres.put(objAlquiler.getCliente().getNif(), objAlquiler);
        }
        rs.close();
        return hashAlquileres;
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
        throw new Exception(ex.getMessage());
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (st != null) {
            st.close();
        }
        if (data != null) {
            data.cerrarConexion();
        }
    }
}
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 32
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Como leer datos de una base de datos

Publicado por Juan (18 intervenciones) el 16/08/2018 18:44:30
Al final le he echo de la siguiente manera:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
public static HashMap<String, Alquiler> filtrarTodosAlquileres() throws Exception {
    DataSource data = null;
    ResultSet rs = null;
    PreparedStatement st;
    st = null;
 
    HashMap<String, Alquiler> hashAlquileres = new HashMap<String, Alquiler>();
 
    try {
        data = new DataSource();
        st = data.getStatement(QUERY);
        rs = data.ejecutarSelect(st);
        while (rs.next()) {
            int identificador = rs.getInt(4);
            String titulo = rs.getString(5);
            boolean mas18 = rs.getBoolean(6);
            boolean alquilado = rs.getBoolean(7);
            Articulo objArticulo = new Articulo(identificador, titulo, mas18,alquilado);
 
            String nif = rs.getString(8);
            String nombre = rs.getString(9);
            String apellido = rs.getString(10);
            Date nacimiento = rs.getDate(11);
            Cliente objCliente =  new Cliente(nif,nombre,apellido, nacimiento);
 
            Date fechaAlquiler = rs.getDate(3);
            Alquiler objAlquiler = new Alquiler(objCliente,objArticulo, fechaAlquiler);
            hashAlquileres.put(objAlquiler.getCliente().getNif(), objAlquiler);
        }
        rs.close();
        return hashAlquileres;
    } catch (SQLException ex) {
        System.err.println(ex.getMessage());
        throw new Exception(ex.getMessage());
    } finally {
        if (rs != null) {
            rs.close();
        }
        if (st != null) {
            st.close();
        }
        if (data != null) {
            data.cerrarConexion();
        }
    }
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar