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 }
You can get the name of a particular column using the getColumnName() method of the ResultSetMetadata interface. This method accepts an integer value representing the index of a column and returns a String value representing the name of the specified column.
You can get the column count in a table using the getColumnCount() method of the ResultSetMetaData interface. On invoking, this method returns an integer representing the number of columns in the table in the current ResultSet object.
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
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"); }
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