2011-01-05 30 views
0

如何迭代table1的所有值(使用java)?如何迭代table1的所有值(使用Java)?

say, table1 has values: 
pkey new_id<fkey> old_id<fkey> 
==================================== 
1 20 1787 
2 24 1789 
3 29 1793 

从上面表p键说,为ID = 1我已经从作为p键的 在其他两个表说TAB2,TAB3两个相应的表中检索的值。 :select new_id,old_id from tab1; 分配给对象;

tab2 
---- 
new_id(pkey) values 
==================== 
20 yu 
32 ty 
23 nm 
24 to 

tab3 
---- 
old_id(pkey) values 
===================== 
1780 ghgjj 
1785 fhfhj 
1787 fdgfh 
1789 fjhgj 
1793 fjjg 

我能够检索ID = 1

"select values from tab2 where newid=+new_id(object)+" 

"select values from tab2 where newid=+old_id(object)+" 

如何遍历表1为所有值? 表来自不同的数据库。 olddatabase1:tab3 newdatabse1:tab1,tab2; tab1是old_id和new_id的映射表。

+0

olddatabase1:TAB3 – reshu 2011-01-05 07:23:00

+0

newdatabse1:TAB1,TAB2;这些表来自不同的数据库。 – reshu 2011-01-05 07:23:57

+0

newdatabse1:映射表为tab1 – reshu 2011-01-05 07:24:37

回答

0

首先,你要加入的表一起使用:

select pkey, t2.values as t2vals, t3.values as t3vals 
from table1 t1, table2 t2, table3 t3 
where t1.new_id = t2.new_id and t1.old_id = t3.old_id 

现在,当你遍历该结果集,你会得到每一行的所有值。

+0

olddatabase1:tab3 newdatabse1:tab1,tab2;这些表来自不同的数据库 – reshu 2011-01-05 07:40:36

3

您可以用这种方式迭代结果集(select * from table)。从JDBC Wikipedia article

Statement stmt = conn.createStatement(); 
try { 
ResultSet rs = stmt.executeQuery("SELECT * FROM MyTable"); 
try { 
    while (rs.next()) { 
     int numColumns = rs.getMetaData().getColumnCount(); 
     for (int i = 1 ; i <= numColumns ; i++) { 
      // Column numbers start at 1. 
      // Also there are many methods on the result set to return 
      // the column as a particular type. Refer to the Sun documentation 
      // for the list of valid conversions. 
      System.out.println("COLUMN " + i + " = " + rs.getObject(i)); 
     } 
    } 
} finally { 
    try { rs.close(); } catch (Exception ignore) { /* Propagate the original exception 
    instead of this one that you may want just logged */ } 
} 
} finally { 
try { stmt.close(); } catch (Exception ignore) { /* Propagate the original exception 
instead of this one that you may want just logged */ } 
}