1

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?

Vikas Gupta
1,2311 gold badge12 silver badges27 bronze badges
asked Sep 2, 2017 at 10:50
1
  • Do you expect something other than dynamic query building? Commented Sep 2, 2017 at 10:57

1 Answer 1

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";
Youcef LAIDANI
60.3k21 gold badges112 silver badges178 bronze badges
answered Sep 2, 2017 at 11:01
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.