Reputation: 2067
after executing a query in Java, say I got the result set like
allan murphy 20 10
kenny rogers 12 22
marry watson 34 5
I want this whole result set into a variable so that I can return the variable and use it in other calling functions. I want to get the whole resultset into a 2D String array, so that later I can access them through indexing.
Question is :: Is it good concept to get the whole resultset into a 2D String array ?? AND How to get it into a 2D String array ?? thankz.
Upvotes: 0
Views: 3301
Reputation: 745
That's how your method for fetching the resultset should look like:
public void getRecord() {
connectDB(); //method returning **con** of type Connection;
String query = "SELECT * From people"; //fetch whole record
Statement stmt;
try {
//execute query on open Connection
stmt = con.createStatement();
System.out.println("Query executed!");
//save result of query
ResulstSet rs;
rs = stmt.executeQuery(query);
//As long as Resultset has a next row...
while (rs.next()) {
//...Construct Object with people passing the Strings and Ints out of the DB
Player player= new Player(rs.getString("name"), rs.getString("surname"),
rs.getInt("number1"), rs.getInt("number2"));
}
stmt.close();
con.close(); //close open Connection to DB
} catch (SQLException e) {
e.printStackTrace();
}
}
and your class that is constructing the player Object could look like this:
public class Player{
private String name;
private String surname;
private int number1;
private int number2;
public Player(String name, String surname, int number1, int number2) {
this.name= name;
this.surname= surname;
this.number1= number1;
this.number2= number2;
}
}
Now you have an object of each row of your Resultset! By adding setter and getters to the Player Class you can extract any information you need.
To display it just add it to a List and call their getter or even implement a method that delivers you the whole set of information at once.
Upvotes: 1
Reputation: 8411
No its not a good concept to get a resultset into a 2d sting array. Use a java object to represent a single row of data. Have fields with getters and setters to represent each column. Convert each row into this object and put it into a List or other Collection. I am not sure what 20 10 and the other numbers represent. But if they are integers then they should be held as integers inside the object instead of converting them to a string and reconverting them back into integers later on.
Upvotes: 0