Rob Audenaerde
Rob Audenaerde

Reputation: 20069

Use getColumnName() or getColumnLabel() for getString()?

I am facing an issue with the SAS jdbc driver I have not seen before, and wondered what would be the correct JDBC behaviour.

Suppose I have some ResultSetMetaData:

metadata.getColumnName(index) -> col1
metadata.getColumnLabel(index) -> Column1

This would be the SQL result when running this query:

SELECT col1 AS Column1

When getting a value from a ResultSet, I expect to use this:

rs.getString("Column1") 

But instead, I seem to have to use:

rs.getString("col1")

Is this to be expected and where my assumptions wrong? Or is this driver-specific behaviour?

Upvotes: 1

Views: 817

Answers (2)

Mark Rotteveel
Mark Rotteveel

Reputation: 109078

In JDBC, you retrieve values of a result set by column label (the alias), not by column name. In the code in your question, the proper way to retrieve a value is using rs.getString("Column1") (or - as it is handled case-insensitive - rs.getString("COLUMN1"))

This is documented in the API, as all String based getters have the following documentation:

Parameters:

columnLabel - the label for the column specified with the SQL AS clause. If the SQL AS clause was not specified, then the label is the name of the column

Historically, JDBC 3 and earlier did not clearly discern between column labels and column names, which - to this day - results in drivers that require you to get by column name, or allow you to get both by column name or label, or return the column name from ResultSetMetaData.getColumnLabel(int) or the column label from ResultSetMetaData.getColumnName(int), or have configuration options to set which behavior to use.

Upvotes: 1

srikanth r
srikanth r

Reputation: 332

Since you are using alias it seems the jdbc is expecting alias in that column name argument.

I found an related link for this : DB alias Resultset. Hope this might be helpful

Upvotes: 1

Related Questions