11

您好,当没有匹配的学生时,我正在尝试出错...它会像这样显示 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);
}
4

5 回答 5

30
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]);
}
于 2013-09-30T13:12:29.667 回答
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。

于 2013-09-30T13:08:43.447 回答
2

开始ResultSetMetaData使用ResultSet#getMetaData()

ResultSetMetaData meta = rs.getMetaData();

然后获取第一列的列名:

String col1Name = meta.getColumnLabel(1);

类似地获取第二列的列名:

String col2Name = meta.getColumnLabel(2);
于 2013-09-30T13:05:54.467 回答
0

获取元数据

ResultSetMetaData metaData = rs.getMetaData();

然后你可以这样做:

String columnName = metaData.getColumnName(int index);
于 2013-09-30T13:06:55.330 回答
0

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

并且不要连接查询参数!

于 2013-09-30T13:08:46.930 回答