Print the data in ResultSet along with column names
I am retrieving columns names from a SQL database through Java. I know I can retrieve columns names from ResultSet
too. So I have this sql query
select column_name from information_schema.columns where table_name='suppliers'
The problem is I don't know how can I get columns names from ResultSet
and my code is
public void getAllColumnNames() throws Exception{
String sql = "SELECT column_name from information_schema.columns where table_name='suppliers'";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery(sql);
// extract values from rs
}
Solution 1:
ResultSet resultSet = statement.executeQuery("SELECT * from foo");
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (resultSet.next()) {
for (int i = 1; i <= columnsNumber; i++) {
if (i > 1) System.out.print(", ");
String columnValue = resultSet.getString(i);
System.out.print(columnValue + " " + rsmd.getColumnName(i));
}
System.out.println("");
}
Reference : Printing the result of ResultSet
Solution 2:
1) Instead of PreparedStatement
use Statement
2) After executing query in ResultSet
, extract values with the help of rs.getString()
as :
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery(sql);
while(rs.next())
{
rs.getString(1); //or rs.getString("column name");
}