I want to p开发者_如何学Cull data from a database. Name, Age, Sex, Location.(maybe more fields)
I want to hold the data in an object similar to how I would expect it to look in a JSON object.
Like:
myData{
row1[name:beavis, age:48, sex:male, location:Joburg]
row2[name:quintus, age:43, sex:, location:Helsinki]
...up to say 500 rows
}
So i'd like to be able to do tempName = row(i).name
and so on in java.
Any suggestions.
// Defines a Person datatype
public class Person {
// fields
private String name;
private int age;
private String location;
// gets the value of a field
public String getName() {
return name;
}
// sets the value of a field
public void setName(aName) {
this.name = aName;
}
}
What I did here was define a Person type with a number of fields. Also I give here an example of a setter and getter for the name field. You can put them in an array or collection. For example:
Person people[] = new Person[2];
people[0] = new Person();
people[0].setName("Alice");
You can also dispense with the setters and getters by making the fields public, but I wouldn't recommend it.
A straight translation of that data structure would be along the lines of
List<Map<String, Object>> myData
so you'd be able to call
tempName = (String) myData.get(i).get("name");
Like the JSON array, this doesn't enforce typing (which you'll have to deal with explicitly in Java) and doesn't limit the fields to only those from the database.
If all the database values are strings, things get cleaner as no casts are necessary.
List<Map<String, String>> myData
tempName = myData.get(i).get("name");
精彩评论