I was wondering how to tell if a column with a certain name exists in a certain database table. I'm using JDBC but if it can be done with pure SQL, it's even better. The solution has to be independent of the DBMS-provider however. I guess I could do that by querying the first row of the table and getting ResultSetMetaData from it, but that assumes there is a row in a table. I would want it to work with an empty table too. Thanks in advance!
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.
The getMetaData() method of ResultSet is used to get the metadata of the records fetched into the ResultSet. The getColumnCount() and getColumnName() methods of ResultSetMetaData interface is used to get the number of columns and name of each column in the table.
You can get them from DatabaseMetaData
.
DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getColumns(...);
It doesn't matter if the table is empty. ResultSetMetaData will still give you information about the types and properties of the columns in a ResultSet object.
You can retrieve general information about the structure of a database with the java.sql.DatabaseMetaData interface.
DatabaseMetaData dbmeta = con.getMetaData();
call getColumns(), to get description of table columns available.
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