I'm really perplexed as to why there's only one value being returned by this set of codes. What I'm trying to do here is to query all the *sense_num* (not primary key) that has the primary key as the parameter. The result should contain 2 or more sense_num and so in every sense_num result, I try to store each element in an int[] array and return the int array respectively. For e.g the result from this query are sense_num 172 & 173. both of them should already be in the array but when i tested the calling function, what it has received is the last value, 173.
I hope you can he开发者_开发知识库lp me with this. Thanks!
public int[] getAllSenseID(int primeID) {
int[] objects = {};
String qry = "SELECT sense_num FROM cebuano_sense WHERE id_num = '" + primeID + "'";
try {
DatabaseConn db = new DatabaseConn("cebuano_wsd");
db.connect();
db.query(qry);
ResultSet result = db.getResult();
ResultSetMetaData data = db.getData();
if (result.next() == true) {
java.sql.ResultSetMetaData rsmd = result.getMetaData();
int colNo = rsmd.getColumnCount();
result.beforeFirst();
int row = 0;
System.out.println(colNo + "::> Column Number");
while (result.next()) {
objects = new int[colNo + 1];
int i = 0;
// object[0] has all the values when I tested it and that's why it only accepts the last //one... how do get or receive both values?
while (i < colNo) {
objects[i] = result.getInt(colNo);
//print to test
System.out.println(objects.length + " >> Count of Objects");
System.out.println(i + " :: " + objects[i] + " >> result");
i++;
}
}
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
return objects;
}
Your line
objects = new int[colNo + 1];
replaces any previous row you have, so you only have the last row you got.
You could have an List<int[]>
which you add to for each row.
Your qry selects one column from the table, so colNo is always 1.
So I think your objects array needs to correspond to row count, and in the results.next loop, you fill out the array. Hope that helps, - MS.
It looks like you're expecting objects[0] to be the first row in your ResultSet, objects[1] to be the second row, etc. What you're actually doing is putting the first column in objects[0], the second column in objects[1], etc. and every row overwrites the previous one. Since your query only has one column, you don't really need the inner loop. Just loop over the ResultSet and put sense_num from each row into the next available element in objects[]. Then objects[] will contain what I think you are expecting.
精彩评论