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());
}
}
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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With