What I'm trying to do is to put data from my database into an Arraylist.
I have a database with wamp, and a simple table: Player, which has a name and a score.
I'm trying to get all of those player into a ArrayList, but what I've tried did not work because my ArrayList is a Player type, and the type which I enter is a String and int.
Here is the code I have for now:
public int test1() {
try {
ArrayList<Player> playerList= new ArrayList<Player>();
BD=ds.getConnection();
Statement s = BD.createStatement();
ResultSet p = s.executeQuery("SELECT * FROM player");
int i = 0;
while(p.next()) {
i++;
playerList.add(p.getString("name")); //did not work
playerList.add(p.getInt("score");
}
s.close();
BD.close();
return 1;
} catch (java.sql.SQLException ex) {
return 0;
}
}
Is someone know something on how to do it, I'll be very thanksfull.
Cordially
The playerList will only accept a Player object, not a String or an int. So create a Player object with the data on hand, and then add it to the list:
while(p.next()) {
i++;
String name = p.getString("name");
int score = p.getInt("score");
Player player = new Player(name, score); // assuming such a constructor exists
// playerList.add(p.getString("name")); //did not work
// playerList.add(p.getInt("score");
// do this:
playerList.add(player);
}
You have a List of Players, and you are trying to add a String and a Integer into it.
ArrayList<Player> playerList= new ArrayList<Player>();
...
playerList.add(p.getString("name")); //did not work
playerList.add(p.getInt("score");
...
You can follow @Hovercraft Full Of Eels suggestion and create a new Player before adding to the list:
Player player = new Player(p.getString("name"), p.getInt("score"));
playerList.add(player);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.