Java ResultSet get Returned Field Names - java

For standard queries I have not had a problem with this. I simply:
ResultSet rs = stmt.executeQuery("SELECT a, b FROM table_name");
ResultSetMetaData rsMetaData = rs.getMetaData();
int numberOfColumns = rsMetaData.getColumnCount();
for (int i = 1; i < numberOfColumns + 1; i++) {
String fieldName = rsMetaData.getColumnName(i);
System.out.print(fieldName + ", ");
}
But the moment I assign a field name to another name, i.e.
ResultSet rs = stmt.executeQuery("SELECT a AS foo, b AS bar FROM table_name");
It throws an error because fields a and b aren't found.
How should I cater to this? Thanks

There is a difference between column name and column label. The methods in ResultSet expect column labels. So you should use the method ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.

Related

How to return multiple rows from result set object to send servlet

I have a class it retrieve number of rows from database but here i return result set object to servlet class and based on those rows i need to display in table when i retrieve table it shows single row only but when i execute same query it shows in Database having two rows may be i didn't return result set object properly can anyone help me to retrieve all the all records from database.
Servlet :
WorkAreaClass wa=new WorkAreaClass();
ResultSet resultSet = wa.workarea(User);
if(resultSet.next())
{
table(resultSet,out);
}
You're calling if(resultSet.next()) before you start to iterate the resultset. After that you'll be on the first row. Then when you enter your while(rs.next()) loop, the cursor is moved to the second row.
You can convert the while loop into a do-while and it won't skip the first row.
Suppose #kayaman solution is correct.
Simply your table should be like this.
public int table( ResultSet rs, PrintWriter out)throws Exception
{
int rowcount=0;
out.println("<P ALIGN='center'><TABLE BORDER=1>");
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
// table header
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TH>" + rsmd.getColumnLabel(i + 1) + "</TH>");
}
out.println("</TR>");
// the data
do {
rowcount++;
out.println("<TR>");
for (int i = 0; i < columnCount; i++) {
out.println("<TD>" + rs.getString(i + 1) + "</TD>");
}
out.println("</TR>");
} while(rs.next());
out.println("</TABLE></P>");
return rowcount;
}
You need to use JDBCRowSet https://docs.oracle.com/javase/tutorial/jdbc/basics/jdbcrowset.html
here is short demo:
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("select * from COFFEES");
JdbcRowSetImpl jdbcRs = new JdbcRowSetImpl(rs);

How to get column name list from java.sql.ResultSet [duplicate]

This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 5 years ago.
try{
connection = dataSource.getConnection();
callableStatement.setInt(2, clientId);
....... // some stuff
resultSet = callableStatement.executeQuery();
}
Now I have a resultSet , but don't know column names? How do I retrive that?
try this...
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnCount = rsmd.getColumnCount();
// The column count starts from 1
for (int i=1; i<=columnCount; i++ ) {
String name = rsmd.getColumnName(i);
// Do stuff with name
}
resultSet.getMetadata() returns you a ResultSetMetaData object that has the column names (e.g. resultSet.getMetadata().getColumnName(1) )
show this:
ResultSetMetaData rsmd = resultSet.getMetaData();
String name = rsmd.getColumnName(1);
you can use ResultSetMetaData
ResultSetMetaData metadata = resultSet.getMetaData();
int columnCount = metadata.getColumnCount();
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = metadata.getColumnName(i);
columns.add(columnName);
}
Following code helps to get the column names of the table.
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsCount = rsmd.getColumnCount();
int i=1;
while (i <= columnsCount){
String columnName = rsmd.getColumnName(i);
i++;
}

Selecting records from two tables

I have the following snippet code:
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * from books");
ResultSetMetaData resMetaData = rs.getMetaData();
int nCols = resMetaData.getColumnCount();
for (int kCol = 1; kCol <= nCols; kCol++) {
System.out.println(resMetaData.getColumnName(kCol));
}
while (rs.next()) {
for (int kCol = 1; kCol <= nCols; kCol++) {
String s = null;
if (kCol == nCols){
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select category_name from categories where category_id = " + rs.getString(kCol));
s = rs1.getString(2);
}
else{
s = rs.getString(kCol);
}
System.out.println(s);
}
}
In my data base I have two tables: books and categories. In both table I have a column *category_id*. The code selects records from the table books. The *category_id* from this table matches the *category_id* from table categories. In this table I have one more row: category_name. I want that the app to write the name from the *category_name* that matches the category_id in table books. I tried but I failed. So, could you give me any idea ?
Thank you

Java - How to get Column name on Result Set [duplicate]

This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 8 years ago.
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);
}
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]);
}
Try this.
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++;
}
Since here your expecting is to get the columns alias instead of column name, so you have to use ResultSetMetaData.getColumnLabel instead of ResultSetmetaData.getColumnName.
Get ResultSetMetaData using ResultSet#getMetaData():
ResultSetMetaData meta = rs.getMetaData();
And then to get column name of 1st column:
String col1Name = meta.getColumnLabel(1);
Similarly to get column name of 2nd column:
String col2Name = meta.getColumnLabel(2);
Get the metadata
ResultSetMetaData metaData = rs.getMetaData();
Then you can do:
String columnName = metaData.getColumnName(int index);
ResultSetMetaData doc
rs.getMetaData().getColumnName(int i);
and do not concat the query param!

viewing results of mysql query in java

In java, when executing a query like :
statement stm = stm.executeQuery("select * from table1");
How can I view the results of this query on the command prompt ?
Thanks for any help
ResultSet rs = stmt.executeQuery("select * from table1");
int columns = rs.getMetaData().getColumnCount();
StringBuilder message = new StringBuilder();
while (rs.next()) {
for (int i = 1; i <= columns; i++) {
message.append(rs.getString(i) + " ");
}
message.append("\n");
}
System.out.println(message); // print table contents

Categories