looping problem while appending data to existing text file
try {
stmt = conn.createStatement();
stmt1 = conn.createStatement();
stmt2 = conn.createStatement();
rs = stmt.executeQuery("select cust from trip1");
rs1 = stmt1.executeQuery("select cust from trip2");
rs2 = stmt2.executeQuery("select cust from trip3");
File f = new File(strFileGenLoc);
OutputStream os = (OutputStream)new FileOutputStream(f,true);
String encoding = "UTF8";
OutputStreamWriter osw = new OutputStreamWriter(os, encoding);
BufferedWriter bw = new BufferedWriter(osw)开发者_运维百科;
}
while ( rs.next() ) {
while(rs1.next()){
while(rs2.next()){
bw.write(rs.getString(1)==null? "":rs.getString(1));
bw.write("\t");
bw.write(rs1.getString(1)==null? "":rs1.getString(1));
bw.write("\t");
bw.write(rs2.getString(1)==null? "":rs2.getString(1));
bw.write("\t");
bw.newLine();
}
}
}
Above code working fine. My problem is 1. "rs" resultset contains one record in the table 2. "rs1" resultset contains 5 record in the table 3. "rs2" resultset contains 5 record in the table
"rs" data is getting recursive.
while writing to the same text file , the output i am getting like
1 2 3
1 12 21
1 23 25
1 10 5
1 8 54
but i need output like below
1 2 3
12 21
23 25
10 5
8 54
What things i need to change in my code.. Please advice
Does this help?
while ( rs.next() ) {
bw.write(rs.getString(1)==null? "":rs.getString(1));
while(rs1.next()){
while(rs2.next()){
bw.write("\t");
bw.write(rs1.getString(1)==null? "":rs1.getString(1));
bw.write("\t");
bw.write(rs2.getString(1)==null? "":rs2.getString(1));
bw.write("\t");
bw.newLine();
}
}
}
You must join the three tables using a common column (often called foreign key). The values in the tables trip2
and trip3
say to which entry they belong in table trip1
. Then you can do this:
select t1.cust, t2.cust, t3.cust
from trip1 t1
join trip2 t2 on t1.id = t2.trip1_id
join trip3 t3 on t1.id = t3.trip1_id
order by t1.id
Now, you will get all the results in a single result set. To get the output you want, print the first column (rs.getString(1)
) only when it changes.
The logic here is flawed. If you only get one result in rs2, you would only show one row, as your while(rs2.next())
will be false after you run through it once. One option would be to iterate over all your result sets, put the values into arrays, and then iterate over them to put the lines to your file. A better solution, as intimated by @Aaron Digulla, would be to only return a single ResultSet
from your database.
精彩评论