2

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());
    }
}
Mohsenuss91
  • 27
  • 1
  • 2
  • 7

4 Answers4

6

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);  
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
6

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.

A4L
  • 17,353
  • 6
  • 49
  • 70
0

You cannot specify * to get the value. For every column your query returns and you wish to print out, specify either:

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

or:

 String all = rs.getString(i);

where "i" is the order of the printed column in the output of your query

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Olesya Razuvayevskaya
  • 1,148
  • 1
  • 7
  • 10
0

The * in your query means select all the columns of the table.

But after executing the query, your result will have all the name of the columns. So to access a result, you have to do:

String a_column_value = rs.getString("a_column_name");
fluminis
  • 3,575
  • 4
  • 34
  • 47