select 数据库中的列表给出空值
select list from database is giving null
我想 select 从数据库中获取一个列表,但它检索到 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;
}
我想 select 从数据库中获取一个列表,但它检索到 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;
}