想要遍历一个结果集中的每一行,包括每一列,但不知道有多少列及每列的类型?

想要遍历一个结果集中的每一行,包括每一列,但不知道有多少列及每列的类型?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class JDBCExample {

public static void main(String[] args) {
    try {
        //System.setProperty("jdbc.drivers","oracle.jdbc.driver.OracleDriver");
        Class.forName("oracle.jdbc.driver.OracleDriver");
        String url = "jdbc:oracle:thin:@localhost:1521:orcl";
        Connection conn = DriverManager.getConnection(url,"scott","123");
        Statement stmt = conn.createStatement();
        ResultSet rs = stmt.executeQuery("select * from dept");

        while (rs.next()){//假如这里不知道列有多少,及每一列的字体类型?
            System.out.print("DeptNo:" + rs.getInt(1));
            System.out.print("\tDeptName:" + rs.getString(2));
            System.out.println("\tLOC:" + rs.getString(3));
        }
        rs.close();
        stmt.close();
        conn.close();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
     catch(SQLException e){
        e.printStackTrace();
    }

}

}

0

3个回答

[code="java"] public static void main(String[] args) throws Exception {
String driver = "oracle.jdbc.driver.OracleDriver";
String url = "jdbc:oracle:thin:@localhost:1521:gdda";
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.getObject(i) + " | ");
        }
        System.out.println();
    }
    rs.close();
    stmt.close();
    conn.close();
}[/code]
0

用 ResultSetMetaData

0

ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
得到结果集的列数
while(rs.next()){
for(int i = 0 ; i <columnCount;i++){
//rs.getString(i)
}
}
类型对你来说重要吗?你这里不是反射封装,如果是反射封装,你应该有映射关系来获取类型
既然不做封装直接返回字符出或者Object 都行啊

0
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!