Initialize a 2D matrix from mySQL recordset in Java
How can i initialize a 2-dimensional matrix from records coming from a database. I know how to do it in a for loop, but how should id o in such a situation:
Statement s = con.createStatement();
ResultSet res = s.executeQuery("my query");
while(res.next()){
//Here i want to put records from
//2 colums say t1 and t2 in a 2D marix say result[][]
}
While this is how i would开发者_StackOverflow fill the matrix:
for(int i=0; i<result.length; i++){
for(int j=0; j<result[i].length; j++){
result[i][j] = value;
}
}
I have no clue how to do this. Please suggest someting?
if you know the number of columns, then the solution would be
for(int i=0; i<result.length; i++){
res.next();
result[i][0] = res.getInt("field1");
result[i][0] = res.getInt("field2");
...
}
if your columns are numbered, you can then use a second loop as per your code and do
for(int i=0; i<result.length; i++){
res.next();
for(int j=0; j<numfields; j++) {
result[i][j] = res.getInt("field"+j);
}
}
精彩评论