I'm a little bit confused with my new SQL query using a union.
I request my firebird db in a java app using jaybird 2.2.8. Usually I parse my ResultSet using the MetaData
ResultSetMetaData metaData = resultSet.getMetaData();
and looping through the columns
for (int i = 1; i <= metaData.getColumnCount(); i++) {
columnName = metaData.getColumnName(i);
int columnType = metaData.getColumnType(i);
switch (columnType) { ...
This was working quite well until I started using a Union in my SQL query. Now the method
metaData.getColumnName(i)
returns an empty string instead of the column name - the column type is valid.
When I use a SQL query without Union everything works as expected and when I test my query in IBExpert all columns have a a valid name.
Any idea whats wrong? Does anybody has a workaround?
Btw. the ResultSet looks quite well in the eclipse debugger
Instead of the getColumnName
you need to use getColumnLabel
. The column name only has a value if the value is guaranteed to come from a single column in a single table, which is not the case in a UNION
. In the case of a UNION
, Firebird handles the name of columns (or the alias if specified) in the first select as aliases (labels) only; it doesn't preserve the column name as a column name that can be returned by getColumnName
.
If you really need to use getColumnName
(eg for compatibility reasons), then you can use the Jaybird connection property columnLabelForName=true
, but this is discouraged because it is not compliant with JDBC. In almost all cases you should use getColumnLabel
instead.
The distinction between column name and column label is subtle, and wasn't really clear in older JDBC specification. Basically column name is the name of the column in the original table, while the column label is the 'name' (or more correctly: label) of the column in the result set. The label is either the alias specified with AS
, or - if no alias is specified - the original column name as returned by getColumnName
.
See also:
Disclosure: I am one of the Jaybird developers