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
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
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);
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
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());
Related
I have a JList model (listModelGrid) with items with labels like this:
LastName, FirstName Spouse // e.g. This is 1st list item with labels
Children // e.g. This is 2nd list item with labels
Street // e.g. This is 3rd list item with labels
City, State Postal // e.g. This is 4th list item with labels
I want to replace Labels with ResultSet.getString method like this:
String labels = "";
labels += resultSet.getString("LastName")+", "+resultSet.getString("FirstName")+" "+
resultSet.getString("Spouse") + "\n";
labels += resultSet.getString("Children") + "\n";
labels += resultSet.getString("Street") + "\n";
labels += resultSet.getString("City")+", "+resultSet.getString("State")+" "+
resultSet.getString("Postal");
I have tried it but stuck in loops:
private String getPrintingLabels(ResultSet rs) throws SQLException {
String str = "";
for (int i = 0; i < listModelGrid.getSize(); i++) {
String element = String.valueOf(listModelGrid.getElementAt(i));
String[] lbls = element.split(",\\s");
str += rs.getString(lbls[0])+", ";
for(int j = 1; j < lbls.length ; j++) {
// Stuck on her
}
String[] lbls2 = element.split("\\s");
str += rs.getString(lbls2[0])+" ";
for(int j = 1; j < lbls2.length ; j++) {
// Stuck on her
}
}
return str;
}
Thanks in advance!
The code in your method is written in a little complicated way.
I have used regex and simplified the code you wanted to write and here it is.
private String getPrintingLabels(ResultSet rs) throws SQLException {
Pattern p = Pattern.compile("([a-zA-Z]+)(,? )?");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < listModelGrid.getSize(); i++) {
String element = String.valueOf(listModelGrid.getElementAt(i));
Matcher m = p.matcher(element);
while(m.find()) {
sb.append(rs.getString(m.group(1)));
if (m.group(2) != null) {
sb.append(m.group(2));
}
}
sb.append(System.getProperty("line.separator")); // helps correctly insert a new line for any platform linux/windows/any
}
System.out.println(sb.toString());
return sb.toString();
}
I don't know if you are familiar with regex but by using regex your job is done quite easily. Also, using String concatenation is not a good idea specially when you have to do it quite much hence I have used StringBuild for same purpose. Also used line.separator property so no matter in what platform you run the code it will have appropriate line in your string. Just use my method instead of yours and see if the desired string the one you wanted.
Also in my code, you won't have to manually manage inserting ", " or " " as that is done automatically as it is present in the string.
Also make sure you import these two or any needed imports,
import java.util.regex.Matcher;
import java.util.regex.Pattern;
I'm pretty new to java and i am not understanding how i would combine these two things. What i am trying to do is reverse the list while also removing the space and capslock in between the letters and add something at the end to the output. Can you tell me what is wrong with what I am doing? This is to be created using a string builder
StringBuilder sb = new StringBuilder("We need ");
for (int i = tools.length - 1; i >= 0; i--) {
sb.append(tools[i]);
}
this part is gonna reverse the list and
for (String s : tools) {
sb.append(s.toLowerCase().trim() + "s, ");
}
this part is gonna lowercase and trim all the non essential stuff. How do I combine these two parts together when Im coding. Really not getting it
so for example if the input is an array of list
String[] tools = {"\tfood", "TABLE", " car ", "Phone"};
the output is going to be We need phones, cars, tables, foods and much more.
StringBuilder sb = new StringBuilder("We need ");
StringBuilder sbend = new StringBuilder();
for (int i = tools.length - 1; i >= 0; i--) {
sb.append(i).append(tools[i]);
sbend.append(tools[tools.length-i-1].toLowerCase().trim() + "s, ");
}
sb.append(sbend);
Just have two stringbuilders. Forget using string functions on integers. integers can't be put to lowercase or trimmed.
For your loop issue you first put your first line items in the first string builder and the reverse part in the second.
then when the loop is finished you join the two.
If this is the output you are expecting
We need phone, car, table, food
Then maybe you can try something like this-
for (int i = tools.length - 1; i >= 0; i--) {
sb.append(tools[i].toLowerCase().replaceAll("\\s+", ""));
if (i != 0) {
sb.append(", ");
}
}
Using StringBuilder and String, it seems to be as simple as below:
StringBuilder sb = new StringBuilder("We need ");
String s;
sb.reverse();
s = sb.substring(0).toLowerCase().replaceAll("\\s+","");
System.out.println(s);
Using only StringBuilder:
StringBuilder sb = new StringBuilder("We need ");
StringBuilder sb0 = new StringBuilder();
for (int i = sb.length() - 1; i >= 0; i--) {
sb0.append(sb.substring(i, i+1).toLowerCase().replace(" ", ""));
}
System.out.println(sb0);
String[] tools = {"\tfood", "TABLE", " car ", "Phone" };
StringBuilder need = new StringBuilder( "We need " );
String del = "";
for( int i = tools.length - 1; i >= 0; --i ){
need.append( del );
need.append( tools[i].trim().toLowerCase() );
need.append( "s" );
del = ", ";
}
need.append( " and much more." );
System.out.println( need.toString() );
This prints
We need phones, cars, tables, foods and much more.
I am trying to insert an element into table from a 2D array.
I have a problem in removing the last comma to write the sql statement in a proper way
This is the code
String m="";
String matInsert = null;
for (int k=0;k<di.mat.length;k++) { //row
for (int j=0;j<di.mat[k].length;j++) {
m+=di.mat[k][j]+", ";
matInsert=new String("INSERT INTO "+ tableName +"("+ff+")"+"values" +"("+m+")");
}
m = m.replaceAll(", $","");
//m=m.substring(0,m.lastIndexOf(","));
System.out.println(matInsert);
stmt1.executeUpdate(matInsert);
}
I tried very much but i did not succeed to remove it
please help.
I commonly use the following structure for this type of thing
String sep = "";
for(...) {
m += (sep+di.mat[k][j]);
sep = ",";
}
It isn't the nicest but it works.
Now, part of the problem in your code is that you are creating matInsert inside the loop then updating m after the loop and not rebuilding it.
Updated code:
String matInsert = null;
for (int k=0;k<di.mat.length;k++) { //row
String m="";
String sep = "";
for (int j=0;j<di.mat[k].length;j++) {
m+= (sep+di.mat[k][j]);
sep = " ,";
}
matInsert="INSERT INTO "+ tableName +"("+ff+")"+"values" +"("+m+")";
System.out.println(matInsert);
stmt1.executeUpdate(matInsert);
}
You can avoid last comma addition with simple logic. It is good idea to omit unnecessary thing on spot, rather than to replace that with another operation.
for (int k=0;k<di.mat.length;k++) { //row
for (int j=0;j<di.mat[k].length;j++) {
m+=di.mat[k][j];
if(j<di.mat[k].length -1){ //This condition will escape you from last comma addition
m+= ", ";
}
}
}
Another point, use StringBuilder#append instead of String + concat to increase the efficiency.
Since m is a String, you can use m.substring(0,m.length()-1) or add and if statement inside the inner loop checking if it is the last index of k and j then don't add a comma at the end.
If you want to remove the last instance of a character in a string, as in delete it, use this:
public class Something
{
public static void main(String[] args)
{
String s = "test";
StringBuilder sb = new StringBuilder(s);
char delval = 'c';
int lastIndex = -1;
for(int i = 0; i < s.length()-1; i++)
{
if(s.charAt(i) == delval)
{
lastIndex = i;
}
}
try{
sb.deleteCharAt(lastIndex);
System.out.println(s);
}
catch(Exception e){
System.out.println("Value not present");
}
}
}
How can I write the following code in scriptella?
It looks like it thinks that I'm trying to compare Set and String, and it does not like the last for loop.
And what is the way to write logical expressions like &&.
Thank you.
<connection id="java" driver="scriptella.driver.janino.Driver"/>
<script connection-id="java>
//some code
if(finalOrderCounter < numberOfEntries){
Set <String> set = new HashSet <String>();
for(int i = 0; i < fieldNames.length; i++){
set.add(fieldNames[i]);
}
for(int i = 0; i < fieldNamesFromXML.length; i++){
set.remove(fieldNamesFromXML[i]);
}
String exception = "";
for(String element:set)
exception += element +"\n";
throw new IOException("Field(s)\n" + exception + "do(es) not exits in the source database");
}
Maybe you can try the "classic" 'for' loop syntax?
StringBuffer exception = new StringBuffer();
for (int i = 0; i < set.size(); ++i) {
String element = (String) set.get(i);
exception.append(element);
exception.append("\n");
}
throw new IOException("Field(s)\n" + exception.toString() + "do(es) not exits in the source database");
BTW, what error are you getting?
I have quite a complex bit of code so I can't show it all, but this part is very simple.
I have a SELECT * FROM myTable which returns a result set to this method which should print it, toUse is the name of the passed result set to this method:
ResultSetMetaData rsmd = (ResultSetMetaData) toUse.getMetaData();
System.out.println("");
int numberOfColumns = rsmd.getColumnCount();
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(", ");
String columnName = rsmd.getColumnName(i);
System.out.print(columnName);
}
System.out.println("");
while (toUse.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(", ");
String columnValue = toUse.getString(i);
System.out.print(columnValue);
}
System.out.println("");
}
Rather than printing out the table I selected from, it is instead excuting a SHOW TABLES; command?
Edit:
I think it has something to do with this running earlier on:
java.sql.DatabaseMetaData meta = con.getMetaData();
results = meta.getTables(null, null, null, new String[]{"TABLE"});
while (results.next()) {
String tableName = results.getString("TABLE_NAME");
if(tableName.equals(parameters)){
return true;
}
}
results.close();
return false;
Unless you've somehow got a broken jdbc driver, there should be no problem between calling .getMetaData() on a Connection before calling .getMetaData() on a ResultSet. You've most likely accidentally altered the value of toUse. One way to validate that you haven't accidentally changed its value is to make your local variable final.
P.S. Instead of this:
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) System.out.print(", ");
String columnValue = toUse.getString(i);
System.out.print(columnValue);
}
Do this:
String delimiter = "";
for (int i = 1; i <= numberOfColumns; i++) {
String columnValue = toUse.getString(i);
System.out.print(delimiter);
System.out.print(columnValue);
delimiter = ", ";
}
No need for a branch condition inside of your loop.