Search code examples
javasql-serverprepared-statementresultset

PreparedStatement ResultSet - Column contains selected column name as String instead of actual values of selected column


Using a PreparedStatement in Java I have run into a weird situation that I couldn't resolve via SO or searching the web.

preStatement = connection.prepareStatement("SELECT ?, Date FROM " + paramTable + " WHERE [...]");
preStatement.setString(1, paramColumn);
ResultSet rs = preStatement.executeQuery();
preStatement.close();

The problem here is that the column paramColumn that is selected from the paramTable table only contains float-Type values in the Database, however when I execute the PreparedStatement the first column comes back with database type nvarchar.

For example if I SELECT MyValue, Date FROM ValueTable the ResultSet would look like

________________________
| MyValue | Date       |
| MyValue | 2014-09-09 |
| MyValue | 2014-09-10 |
....

while it should look like

________________________
| MyValue | Date       |
| 26,567  | 2014-09-09 |
| 28,623  | 2014-09-10 |
....

When I execute that SQL Statement in the Management Console I get the correct values no problem but in Java the column always contains the column name as a String.


Solution

  • Just concatenate the column name in the query string

    preStatement = connection.prepareStatement("SELECT "+paramColumn+", Date FROM " + paramTable + " WHERE [...]");