Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing all columns from "Select *" query in java

Tags:

java

sql

I want to know how to print "Select *" query in java ? I tried this function but it give me this message "invalid column name "after execution.

public static void ask() throws Exception {
    try {
        java.sql.Statement s= conn.createStatement();
        ResultSet rs = s.executeQuery("SELECT * FROM DB1.T1");

        System.out.println("**************Resultats**************");
        while ( rs.next() ) {
            String all = rs.getString("*");
            System.out.println(all);
        }
        conn.close();
    } catch (Exception e) {
        System.err.println("exception! ");
        System.err.println(e.getMessage());
    }
}
like image 945
Mohsenuss91 Avatar asked Jul 22 '26 15:07

Mohsenuss91


2 Answers

You could use the following generic approach:

c = getConnection();
st = c.createStatement();
rs = st.executeQuery("select * from MY_TABLE");

ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();

while(rs.next()) {
    for(int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
        Object object = rs.getObject(columnIndex);
        System.out.printf("%s, ", object == null ? "NULL" : object.toString());
    }
    System.out.printf("%n");
}

It gets the Metadata from the the returned Resultset to determine the number of columns the result set contains and does a simple iteration. This works even if your SQL is select col1, col2 from MY_TABLE. In such a case columnCount would be 2.

like image 144
A4L Avatar answered Jul 25 '26 06:07

A4L


This line is the problem:

String all = rs.getString("*");

you have to provide the column name in the getString() method. Presently it assumes * as a column name which is not correct and hence shows an error.

You have to provide the column name in that like this:

String all = rs.getString("Column_Name");

EDIT:-

You may try this if you dont want to write the names of the columns

ResultSetMetaData md = rs.getMetaData(); 
int colCount = md.getColumnCount();  

for (int i = 1; i <= colCount ; i++){  
String col_name = md.getColumnName(i);  
System.out.println(col_name);  
}
like image 37
Rahul Tripathi Avatar answered Jul 25 '26 04:07

Rahul Tripathi