2

I have a connection with oracle database like this:

String selectSQL = "SELECT ?,supplier_name FROM supplier WHERE supplier_id = ?";
        PreparedStatement preparedStatement = con.prepareStatement(selectSQL);
        preparedStatement.setString(1, "supplier_id");
        preparedStatement.setInt(2, 1);
        ResultSet rs2 = preparedStatement.executeQuery();

        while (rs2.next()) {
            String userid = rs2.getString(1);
            String username = rs2.getString(2);
            System.out.println(userid);
            System.out.println(username);
        }
        con.close();
    };

The problem is that the second parameter is passed like I want which means that

supplier_id = 1

but I have a problem with the first parameter. Each time only the string is beeing passed so my query looks like

select "supplier_id", supplier_name FROM supplier WHERE supplier_id = ?

instead of

select supplier_id, supplier_name FROM supplier WHERE supplier_id = ?

Because of that as a result I don't get the value from the table coressponding to supplier_id but the string "supplier_id". What am I doing wrong? What should I change to get the value not string?

EdXX
  • 872
  • 1
  • 14
  • 32

1 Answers1

5

It is not possible to create dynamic queries this way, you have to use the normal string operations. Parameters can only be used for values, like Strings, Numbers, etc., not for names.

In your case it would be possible to do something like

String sqlTemplate = "SELECT <id_column>,supplier_name FROM supplier WHERE supplier_id = ?";
String selectSQL = sqlTemplate.replace("<id_column>", "supplier_id");
user3151902
  • 3,154
  • 1
  • 19
  • 32