Search code examples
javasqlprepared-statement

Is it possible to bind variables in select clause?


Can we bind variables in select clause like this:

String sql = "select ? name from user";
PreparedStatement = conn.prepareStatement(sql);
pstmnt.setString(1, "name");

or can we bind variables in where clause only?


Solution

  • You can bind variables wherever you want. But you cannot bind identifier names e.g. database, table and column names (which is what you seem to be trying to do). The result of your sample code will look something like this:

    name
    ----
    name
    name
    name
    

    I.e. it will select the constant string literal 'name' for each row in the table.