Can anyone suggest hot to print column name and value in output in console:
I have below code which only prints the value of the column, but i need to print value with correspondence column name as well:
import java.io.*;
import java.sql.*;
public class RetrieveFile {
public static void main(String args[]) throws Exception {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@123.32.23.123:8080/orcl", "test1", "******");
PreparedStatement ps = con.prepareStatement("select * from MSG where MID='1234'");
ResultSet rs = ps.executeQuery();
try {
printResultColumns(rs);
} catch (SQLException e) {
System.err.println(e.getMessage());
}
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void printResultColumns(ResultSet resultSet) throws SQLException, IOException {
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnCount = rsmd.getColumnCount();
while (resultSet.next()) {
// you get a single result row in here, not the entire ResultSet
for (int i = 1; i <= columnCount; i++) {
switch (rsmd.getColumnType(i)) {
case Types.VARCHAR:
case Types.LONGVARCHAR:
case Types.CHAR:
System.out.println(resultSet.getString(i));
break;
case Types.DOUBLE:
System.out.println(resultSet.getDouble(i));
break;
case Types.INTEGER:
System.out.println(resultSet.getInt(i));
break;
case Types.DATE:
System.out.println(resultSet.getDate(i).toString());
break;
case Types.TIMESTAMP:
System.out.println(resultSet.getTimestamp(i).toString());
break;
case Types.BOOLEAN:
System.out.println(resultSet.getBoolean(i));
break;
case Types.DECIMAL:
case Types.NUMERIC:
System.out.println(resultSet.getBigDecimal(i));
break;
default:
//System.out.println(rsmd.getColumnClassName(i)
}
}
}
}
}
Current Output:- null 1961108001406E00 389 OUR NOW USD
Expected Output:- Col1-null Col2-1961108001406E00 Col3-389 Col4-OUR Col5-NOW Col6-USD
OR Expected Out put:-
Col1 Col2 Col3 Col4 Col5 Col6
-----------------------------------
null 1961 389 our now usd