我想从数据库中选择一个列表,但它返回null
道方法:
public static List<Matiere> getAll() throws ClassNotFoundException, SQLException {
Matiere M = null;
Connection cnx = Connect.getConnection();
String req = "select* from matiere";
PreparedStatement st = cnx.prepareStatement(req);
ResultSet rs = st.executeQuery();
rs.next();
System.out.println("cc " + M);
return (List<Matiere>) M;
}
循环jsp
<table border=1 width=80% align=center>
<tr><th>ID</th><th>Libellé</th></tr>
<%
List<Matiere>lg=AdminDAO.getAll();
for(Matiere m:lg){ %>
<tr>
<td> <%=m.getId() %> </td>
<td><%=m.getLibelle() %> </td>
</tr>
<% } %>
</table>
如何解决
问题是您没有将结果集填充到List
。为了从中获得结果List
,您首先需要填充它。
例如,请检查以下代码,
public static List<Matiere> getAll()
{
List<Matiere> matiere = new ArrayList<>();
try
{
String sql = "SELECT * FROM matiere";
Connection con = Connect.getConnection();
PreparedStatement statement = con.prepareStatement(SQL);
ResultSet rs = statement.executeQuery(SQL);
while(rs.next()) {
Matiere m = new Matiere();
//Here add your database fields
m.setId(rs.getString("id"));
m.setLibelle(rs.getString("libelle"));
matiere.add(m);
}
}
catch(SQLException e) {
// Log any exceptions ...
}
finally() {
// Always close your JDBC resources
try {
if (statement != null) {
statement.close();
statement=null;
}
}
catch(SQLException e) {
// Couldn't close statement
}
}
return matiere;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句