用列名打印整个表

我目前正在学习 SQL 并且正在使用 MS SQL Server 2017。


我能够打印出包含除列名之外的所有数据的特定表,但我真的不知道如何检索它们。


这是我的代码的一部分(我删除了代码示例的 try catch)


Connection conn = null;

ResultSet rs = null;

String query = "SELECT * FROM Example";

ResultSetMetaData rsmd = null;


Class.forName(driver);

conn = DriverManager.getConnection(connectionUrl, userName, password);

Statement mS = conn.createStatement();

System.out.println("Verbindung wurde hergestellt");

rs = mS.executeQuery(query);

rsmd = rs.getMetaData();

int columnsNumber = rsmd.getColumnCount();

while (rs.next()) {

    for(int i = 1; i <= columnsNumber; i++) {

        System.out.print(rs.getString(i)+ " ");

    }

    System.out.println();

}


LEATH
浏览 177回答 1
1回答

烙印99

您应该从一个循环开始,为每个列 index打印rsmd.getColumnLabel(int column)。// header&nbsp; &nbsp; for(int i = 1; i <= columnsNumber; i++) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.print(rsmd.getColumnLabel(i)+ " ");&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println();// data&nbsp; &nbsp; while(rs.next()) {&nbsp; &nbsp; &nbsp; &nbsp; for(int i = 1; i <= columnsNumber; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.print(rs.getString(i)+ " ");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println();&nbsp; &nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java