Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieve column names from java.sql.ResultSet

Tags:

java

jdbc

People also ask

How do I get a list of column names in ResultSet?

You can get the name of a particular column using the getColumnName() method of the ResultSetMetadata interface. This method accepts an integer value representing the index of a column and returns a String value representing the name of the specified column.

How can I get column names from a table in SQL query?

To get the column name of a table we use sp_help with the name of the object or table name. sp_columns returns all the column names of the object. The following query will return the table's column names: sp_columns @table_name = 'News'

How do you find the information about columns in a ResultSet object?

You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.


You can get this info from the ResultSet metadata. See ResultSetMetaData

e.g.

 ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
 ResultSetMetaData rsmd = rs.getMetaData();
 String name = rsmd.getColumnName(1);

and you can get the column name from there. If you do

select x as y from table

then rsmd.getColumnLabel() will get you the retrieved label name too.


In addition to the above answers, if you're working with a dynamic query and you want the column names but do not know how many columns there are, you can use the ResultSetMetaData object to get the number of columns first and then cycle through them.

Amending Brian's code:

ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();

// The column count starts from 1
for (int i = 1; i <= columnCount; i++ ) {
  String name = rsmd.getColumnName(i);
  // Do stuff with name
}

You can use the the ResultSetMetaData (http://java.sun.com/javase/6/docs/api/java/sql/ResultSetMetaData.html) object for that, like this:

ResultSet rs = stmt.executeQuery("SELECT * FROM table");
ResultSetMetaData rsmd = rs.getMetaData();
String firstColumnName = rsmd.getColumnName(1);

This question is old and so are the correct previous answers. But what I was looking for when I found this topic was something like this solution. Hopefully it helps someone.

// Loading required libraries    
import java.util.*;
import java.sql.*;

public class MySQLExample {
  public void run(String sql) {
    // JDBC driver name and database URL
    String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    String DB_URL = "jdbc:mysql://localhost/demo";

    // Database credentials
    String USER = "someuser"; // Fake of course.
    String PASS = "somepass"; // This too!

    Statement stmt = null;
    ResultSet rs = null;
    Connection conn = null;
    Vector<String> columnNames = new Vector<String>();

    try {
      // Register JDBC driver
      Class.forName(JDBC_DRIVER);

      // Open a connection
      conn = DriverManager.getConnection(DB_URL, USER, PASS);

      // Execute SQL query
      stmt = conn.createStatement();
      rs = stmt.executeQuery(sql);
      if (rs != null) {
        ResultSetMetaData columns = rs.getMetaData();
        int i = 0;
        while (i < columns.getColumnCount()) {
          i++;
          System.out.print(columns.getColumnName(i) + "\t");
          columnNames.add(columns.getColumnName(i));
        }
        System.out.print("\n");

        while (rs.next()) {
          for (i = 0; i < columnNames.size(); i++) {
            System.out.print(rs.getString(columnNames.get(i))
                + "\t");

          }
          System.out.print("\n");
        }

      }
    } catch (Exception e) {
      System.out.println("Exception: " + e.toString());
    }

    finally {
      try {
        if (rs != null) {
          rs.close();
        }
        if (stmt != null) {
          stmt.close();
        }
        if (conn != null) {
          conn.close();
        }
      } catch (Exception mysqlEx) {
        System.out.println(mysqlEx.toString());
      }

    }
  }
}

SQLite 3

Using getMetaData();

DatabaseMetaData md = conn.getMetaData();
ResultSet rset = md.getColumns(null, null, "your_table_name", null);

System.out.println("your_table_name");
while (rset.next())
{
    System.out.println("\t" + rset.getString(4));
}

EDIT: This works with PostgreSQL as well