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

您好,当没有匹配的学生时,我正在尝试犯一个错误…它将以这种方式显示, 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);

}

回答:

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]);

}

以上是 Java-如何获取结果集上的列名 的全部内容, 来源链接: utcz.com/qa/408842.html

回到顶部