JeraldPunx JeraldPunx - 2 days ago 3
Java Question

Java - How to get Column name on Result Set

Hello I'm trying to make an error when there is no matched student...
and it will display like this

No matching records found
and I want the column name still the same but still not figuring it out... can some one tell me if this is right??

Heres my function for that... and I add comment there where I put the error... but i don't know how to get the columnname

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


I try like this but still gave me NULL!!!
this code is below of
empty = false;


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

Answer
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]);
}
Comments