我要做的是返回调用该方法的任何类型的对象的java列表。
List<Playlist> playlist = Table.selectAll();
这些java对象(在本例中为Playlist)应该都包含我的SQL ResultSet中的一行值。
public class Table extends Database {
public List<this> selectAll() {
List<this> newList = new List<this>();
String tableName = this.getClass().getSimpleName().toLowerCase();
Field[] fields = this.getClass().getDeclaredFields();
Connection connection = getConnection();
PreparedStatement preStat = null;
ResultSet resultSet = null;
try {
preStat = connection.prepareStatement("SELECT * FROM " + tableName);
resultSet = getFromDB(preStat);
} catch (SQLException e) {
e.printStackTrace();
}
// create a list of Objects of class ‘this’ (in this case Playlist)
// and using the fields obtained from .getDeclaredFields()
// assign values to each Object from the ‘preStat’ results
// then put those objects into ‘newList’
return newList;
}
}
我在这里做错了什么?我应该将List传递给方法而不是返回,但是我如何从每个ResultSet创建一个Object,使用.getDeclaredFields()为其分配值然后将对象分配给List?
答案 0 :(得分:0)
List<this> newList = new List<this>();
不会起作用,必须是
List<PlayList> newList = new List<>();
然后在你的评论中做
while (resultSet.next()) {
PlayList l = new PlayList();
l.setId(resultSet.getInt(1));
l.setYourStringField(resultSet.getString(2));
l.setAnotherStringField(resultSet.getString(3));
newList.add(l);
}
resultSet.close();
preStat.close();
connection.close();
成为PlayList对象的setId
,setYourStringField
和setAnotherStringField
属性设置器。