0

I am currently learning SQL and am using MS SQL Server 2017.

I am able to print out a specific table with all the data except the column names and I don't really know how to retrieve them.

Here are parts of my code (I removed the try catch for the code sample)

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();
}

EDIT: I want them to be printed out only once so that I have some kind of "header"

Remph
  • 323
  • 1
  • 4
  • 14

1 Answers1

3

You should start with a loop to print rsmd.getColumnLabel(int column) for each column index .

// header
    for(int i = 1; i <= columnsNumber; i++) {
        System.out.print(rsmd.getColumnLabel(i)+ " ");
    }
    System.out.println();

// data
    while(rs.next()) {
        for(int i = 1; i <= columnsNumber; i++) {
            System.out.print(rs.getString(i)+ " ");
        }
        System.out.println();
    }
Arnaud
  • 17,229
  • 3
  • 31
  • 44
  • Okay, that works, but is it possible to retrieve these only once so that I have them as a "header" – Remph Aug 17 '18 at 07:09
  • Sure, just put this loop before your `while (rs.next())` loop and you're done (see the edited answer). – Arnaud Aug 17 '18 at 07:13