Reputation: 27
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());
}
}
Upvotes: 2
Views: 20401
Reputation: 1168
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
Upvotes: 0
Reputation: 172378
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);
}
Upvotes: 6
Reputation: 17595
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
.
Upvotes: 6
Reputation: 4039
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");
Upvotes: 0