问题
How can I have a var which contains all the records I get from a resultset?
So far I have this code:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue += resultado;
}
jTextPane2.setText(jTextPane2.getText() + columnValue + ", ");
}
I want that when resultado gets the value from the rs.getString(i), fills the var columnValue so that I have a var which SHOULD have all the records I get from the rs, but is not working. Any help?
The result I get is:
(id_tlf, cod_area)
1+58, 1+582+104, 1+582+1043+60
so as you see, the first 2 results repeat in every row
回答1:
Please prefer a StringBuilder to creating lots of String temporary values (they pollute the intern cache for one thing). Next, you don't need to store each column in another local variable. Basically, I would do something like
StringBuilder sb = new StringBuilder();
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
if (i != 1) {
sb.append(", ");
}
sb.append(rs.getString(i));
}
sb.append(System.lineSeparator());
}
jTextPane2.setText(sb.toString());
Note the above clears jTextPane2, if you intend to append then you could change the first line to to something like
StringBuilder sb = new StringBuilder(jTextPane2.getText());
sb.append(System.lineSeparator()); // <-- start the next line... and then iterate rs
回答2:
Not sure if I understand right, but it could be something like this:
while (rs.next()) {
for (int i = 1; i <= columnCount; i++) {
String resultado = "";
resultado = rs.getString(i);
columnValue+=resultado;
}
columnValue+=", ";
}
jTextPane2.setText(columnValue);
回答3:
your problem is your columnValue and your jTextPane.
When you want to add the text to your jTextPane, you are adding the text you already have inside the textpane AND you add add the columnValue text (which is already within the textpane).
Within your for loop, you write the following to get the result:
columnValue+=resultado;
Here you should write
columnValue=resultado;
This should fix your problem.
I hope that I could help you.
Best regards. Levkaz
回答4:
You are accumulation the column value each inner iteration (without reinitializing to the empty string each outer iteration):
columnValue+=resultado;
And you are accumulation the total message each outer iteration:
jTextPane2.setText(jTextPane2.getText() + columnValue + ", ");
Pick one :-)
I'd recommend using (Java 8) StringJoiner, and only updating jTextPane2 at the end of the loop:
StringJoiner sj = new StringJoiner(", ");
while (rs.next()) {
StringBuilder columnValue = new StringBuilder();
for (int i = 1; i <= columnCount; i++) {
columnValue.append(rs.getString(i));
}
sj.add(columnValue.toString());
}
jTextPane2.setText(sj.toString());
来源:https://stackoverflow.com/questions/36636398/troubles-getting-results-from-resultset