I have a connection with oracle like this:
Connection con=getConnection();
String query="select ?, ? from my_table";
PreparedStatement p=con.prepareStatement(query);
p.setString(1, "id");
p.setString(2, "lastName ");
ResultSet rs=p.executeQuery();
Everything is ok here but I'am wondering how doing this when you don't have a fixed number of parameters you want to select.
For example, in above, I want to select only 'id' and 'lastName'. But those parameters are taken from different Java method and depends on the situation that method can return a different number of parameters which I would like to pass to my SQL select.
I don't know the parameters in advance so once I can get only 'id' and 'lastName' but next time 'id','firstName','address' and 'city'. Then I want to pass them to SQL query. Can anyone tell me how to use parameters in sql query in such case?
-
Do you expect something other than dynamic query building?Mehdi Javan– Mehdi Javan2017年09月02日 10:57:48 +00:00Commented Sep 2, 2017 at 10:57
1 Answer 1
When you don't know how much parameter you required. Then make a program that accept String array/list then join them comma delimiter. This should solve your problem.
e.g.
String paramsList = new String[]{"id", "first_name", "last_name"};
If you are using Java8 you can use String.join like :
String params = String.join(",", paramsList);
Then write your sql statement like
String query="select " + params + " from my_table";
Comments
Explore related questions
See similar questions with these tags.