Retrieve column names from java.sql.ResultSet

2019-01-01 03:13发布

With java.sql.ResultSet is there a way to get a column's name as a String by using the column's index? I had a look through the API doc but I can't find anything.

标签: java jdbc
10条回答
萌妹纸的霸气范
2楼-- · 2019-01-01 03:44

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);
查看更多
时光乱了年华
3楼-- · 2019-01-01 03:49

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

    }
  }
}
查看更多
浅入江南
4楼-- · 2019-01-01 03:52

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.

查看更多
素衣白纱
5楼-- · 2019-01-01 03:52

The SQL statements that read data from a database query return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The **java.sql.ResultSet** interface represents the result set of a database query.

  • Get methods: used to view the data in the columns of the current row being pointed to by the cursor.

Using MetaData of a result set to fetch the exact column count

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

http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSetMetaData.html

and further more to bind it to data model table

   public static void main(String[] args) {
     Connection conn = null;
     Statement stmt = null;
     try{
      //STEP 2: Register JDBC driver
      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection
      System.out.println("Connecting to a selected database...");
      conn = DriverManager.getConnection(DB_URL, USER, PASS);
      System.out.println("Connected database successfully...");

      //STEP 4: Execute a query
      System.out.println("Creating statement...");
      stmt = conn.createStatement();

      String sql = "SELECT id, first, last, age FROM Registration";
      ResultSet rs = stmt.executeQuery(sql);
      //STEP 5: Extract data from result set
      while(rs.next()){
         //Retrieve by column name
         int id  = rs.getInt("id");
         int age = rs.getInt("age");
         String first = rs.getString("first");
         String last = rs.getString("last");

         //Display values
         System.out.print("ID: " + id);
         System.out.print(", Age: " + age);
         System.out.print(", First: " + first);
         System.out.println(", Last: " + last);
      }
      rs.close();
     }catch(SQLException se){
      //Handle errors for JDBC
      se.printStackTrace();
     }catch(Exception e){
      //Handle errors for Class.forName
      e.printStackTrace();
     }finally{
      //finally block used to close resources
      try{
         if(stmt!=null)
            conn.close();
      }catch(SQLException se){
      }// do nothing
      try{
         if(conn!=null)
            conn.close();
     }catch(SQLException se){
         se.printStackTrace();
       }//end finally try
     }//end try
      System.out.println("Goodbye!");
     }//end main
    }//end JDBCExample

very nice tutorial here : http://www.tutorialspoint.com/jdbc/

ResultSetMetaData meta = resultset.getMetaData();  // for a valid resultset object after executing query

    Integer columncount = meta.getColumnCount();

    int count = 1 ; // start counting from 1 always

    String[] columnNames = null;

    while(columncount <=count){

    columnNames [i] = meta.getColumnName(i);

    }

    System.out.println (columnNames.size() ); //see the list and bind it to TableModel object. the to your jtbale.setModel(your_table_model);
查看更多
浪荡孟婆
6楼-- · 2019-01-01 03:53

When you need the column names, but do not want to grab entries:

PreparedStatement stmt = connection.prepareStatement("SHOW COLUMNS FROM `yourTable`");

ResultSet set = stmt.executeQuery();

//store all of the columns names
List<String> names = new ArrayList<>();
while (set.next()) { names.add(set.getString("Field")); }

NOTE: Only works with MySQL

查看更多
初与友歌
7楼-- · 2019-01-01 03:54

@Cyntech is right.

Incase your table is empty and you still need to get table column names you can get your column as type Vector,see the following:

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

Vector<Vector<String>>tableVector = new Vector<Vector<String>>(); 
boolean isTableEmpty = true;
int col = 0;

 while(rs.next())
    {
      isTableEmpty = false;  //set to false since rs.next has data: this means the table is not empty
       if(col != columnCount)
          {
            for(int x = 1;x <= columnCount;x++){
                 Vector<String> tFields = new Vector<String>(); 
                 tFields.add(rsmd.getColumnName(x).toString());
                 tableVector.add(tFields);
             }
            col = columnCount;
          }
     } 


      //if table is empty then get column names only
  if(isTableEmpty){  
      for(int x=1;x<=colCount;x++){
           Vector<String> tFields = new Vector<String>(); 
           tFields.add(rsmd.getColumnName(x).toString());
           tableVector.add(tFields);
        }
      }

 rs.close();
 stmt.close();

 return tableVector; 
查看更多
登录 后发表回答