Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting column names in JDBC

Tags:

java

sql

jdbc

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!

like image 730
mikkis Avatar asked Aug 01 '11 09:08

mikkis


People also ask

How do I get columns from ResultSet?

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.

How do I get columns in Java?

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.


3 Answers

You can get them from DatabaseMetaData.

DatabaseMetaData meta = connection.getMetaData();
ResultSet rs = meta.getColumns(...);
like image 150
duffymo Avatar answered Sep 29 '22 09:09

duffymo


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.

like image 26
dogbane Avatar answered Sep 29 '22 11:09

dogbane


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.

like image 23
Swagatika Avatar answered Sep 29 '22 11:09

Swagatika