Java - 如何在结果集上获取列名称

时间:2013-09-30 13:03:44

标签: java mysql database jdbc

你好,我正在尝试在没有匹配的学生时犯错误... 它将显示如下 No matching records found我希望列名仍然相同,但仍然没有弄清楚...有人可以告诉我这是否正确吗?

继承我的功能...我在那里添加评论我把错误...但我不知道如何获取列名

public void SearchTableStudent() {
        String tempSearchValue = searchStudent.getText().trim();
        boolean empty = true;
        sql = "SELECT student_id as 'Student ID',"
                + "concat(lastname, '  ,  ', firstname, ' ', middlename) as 'Name'"
                + "FROM user "
                + "WHERE CAST(student_id as CHAR) LIKE '%" + tempSearchValue + "%'";
        try {
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            while(rs.next()) {
                table.setModel(DbUtils.resultSetToTableModel(rs));
                empty = false;
            }
            if(empty) {
                String error = "";
                table.setModel(new javax.swing.table.DefaultTableModel(
                    new Object [][] {
                        {"No matching records found",null}
                    },
                    new String [] {
     /** I WANT TO PUT THE SAME COLUMN NAME ON MY DATABASE SELECTED BUT DON't Know
 WHAT FUNCTION TO DO*/
                    }
                ));
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e.getMessage());
        }
    }

我尝试这样但仍然给我NULL! 此代码低于empty = false;

for(int i=0; i<table.getColumnCount(); i++) {
    test[i] = table.getColumnName(i);
}

5 个答案:

答案 0 :(得分:29)

ResultSetMetaData metaData = resultSet.getMetaData();
int count = metaData.getColumnCount(); //number of column
String columnName[] = new String[count];

for (int i = 1; i <= count; i++)
{
   columnName[i-1] = metaData.getColumnLabel(i);
   System.out.println(columnName[i-1]);
}

答案 1 :(得分:4)

试试这个。

      ResultSetMetaData meta = resultset.getMetaData(); 

      Integer columncount = meta.getColumnCount();

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

      String[] columnNames = new String[columncount];

      while(count<=columncount){

         columnNames [count-1] = meta.getColumnLabel(count);
         count++;

      }

由于您希望获得列别名而不是列名,因此您必须使用ResultSetMetaData.getColumnLabel而不是ResultSetmetaData.getColumnName。

答案 2 :(得分:2)

使用ResultSetMetaData获取ResultSet#getMetaData()

ResultSetMetaData meta = rs.getMetaData();

然后获取第一列的列名:

String col1Name = meta.getColumnLabel(1);

与获取第二列的列名相似:

String col2Name = meta.getColumnLabel(2);

答案 3 :(得分:0)

获取元数据

ResultSetMetaData metaData = rs.getMetaData();

然后你可以这样做:

String columnName = metaData.getColumnName(int index);

答案 4 :(得分:0)

rs.getMetaData().getColumnName(int i);

并且不要连接查询参数!