遍历ResultSet元素

import java.sql.*;


public class EnuResultSet {
public static void main(String[] args) throws Exception {  
    String driver = "oracle.jdbc.driver.OracleDriver";  
    String url = "jdbc:oracle:thin:@localhost:1521:orcl";  
    String user = "scott";  
    String pass = "123";  
    //   
    Class.forName(driver);  
    Connection conn = DriverManager.getConnection(url, user, pass);  
    Statement stmt = conn.createStatement();  
    ResultSet rs = stmt.executeQuery("select * from dept");  
      
    ResultSetMetaData rsmd = rs.getMetaData();  
    int columnCount = rsmd.getColumnCount();  
    // 输出列名  
    for (int i=1; i<=columnCount; i++){  
        System.out.print(rsmd.getColumnName(i));  
        System.out.print("(" + rsmd.getColumnTypeName(i) + ")");  
        System.out.print(" | ");  
    }  
    System.out.println();  
    // 输出数据  
    while (rs.next()){  
        for (int i=1; i<=columnCount; i++){  
            System.out.print(rs.getString(i) + " | ");  
        }  
        System.out.println();  
    }  
    rs.close();  
    stmt.close();  
    conn.close();  

}

但如果是任意一个返回的结果集,比如数据库元数据DatabaseMedata中的多个方法返回的都是ResultSet对象,如:getAttributes() ,getBestRowIdentifier() ,getTypeInfo()等方法,这时如何遍历这个对象的每一列,上面的方法就处理不了了?

我已解决:
import java.sql.*;
public class TestMetaData {

public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
ResultSetMetaData rm;
DatabaseMetaData dmd;
int   n=1;


String url = "jdbc:oracle:thin:@localhost:1521:orcl";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(url,"scott","123");
dmd = conn.getMetaData();
if(dmd == null){
System.out.println("no Meta avaliable.");
}else{
System.out.println("Database Name:"+dmd.getDatabaseProductName());
System.out.println("Database Version:"+ dmd.getDatabaseProductVersion());
System.out.println("Database Driver:"+ dmd.getDriverName());
System.out.println("Database DriverVerion:"+ dmd.getDriverVersion());
System.out.println("Database DataBase TypeList:");
rs = dmd.getTypeInfo();
            rs.next();
for(int   i=1;i <=n;i++){
if(rs.getString(i)!=null){
n+=1;}
}
while(rs.next()){
for (int i1=1;i1<n;i1++){
System.out.print("\t" + rs.getString(i1)+"\t");
}
System.out.println();
}
rs.close();
}
stmt = conn.createStatement();
String sql = "select * from dept";
rs = stmt.executeQuery(sql);
System.out.println("The data table structure info:");
rm = rs.getMetaData();
int columnNum = rm.getColumnCount();
System.out.println("Num \tcolumnName \tDataType");
for (int i=1;i<=columnNum;i++){
System.out.println(i+"\t"+rm.getColumnName(i)+"\t"+rm.getColumnTypeName(i));
}
}catch (Exception e){
e.printStackTrace();
}finally{
CloseConn.closeConnEtc(rs,conn,stmt);
}
}


}

你可能感兴趣的:(ResultSet)