0

I am trying to fetch the select queries in one string. This is what I want. I tried different ways, but could not solve. This is my code:

ResultSet rs = st.executeQuery("select city_ID from user where name = '"    + name + "'");

        String sql = "";
        while (rs.next()) {
            sql += "select * from city where ID = " +rs.getInt(1) + ",";
        }
        sql = sql.substring(0, sql.length()-1);     
        PreparedStatement stmt = con.prepareStatement(sql);
        rs = stmt.executeQuery();

I did this, but there are errors. How can I solve it? Basically, I want to add many queries in one string, and execute that string. Then I need them in something like resultSet.

Burak Keceli
  • 933
  • 1
  • 15
  • 31

1 Answers1

2

I'm little confused from what are you trying to achieve but i guess you need this:

select * from city as c inner join user as u on (c.ID = u.city_ID) 
where u.name = ?;

Then you need only execute this one query and you have desired results.

But also as @dystroy mentioned if you want to use your approach you need at first fetch ids from User into some List<Integer> and then create some List<String> that will hold your queries or use IN clause in your query.

Pseudo-code:

// getting ids from User

List<Integer> cityIds = new ArrayList<Integer>();
String query = "select city_ID from user where name = ?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
   cityIds.add(rs.getInt("city_ID"));
}

// dynamically create your query

StringBuilder builder = new StringBuilder("select * from city where ID in (");
for (int i = 0; i < cityIds.size(); i++) {
   builder.append("?");
   if (i < cityIds.size() - 1) {
      builder.append(",");
   }
}
builder.append(")");

// creating PreparedStatement

ps = con.prepareStatement(builder.toString());

// adding params to query

int index = 1;
for (Integer id: cityIds) {
   ps.setInt(index, id);
   index++;
}

ResultSet rs = ps.executeQuery();
while (rs.next()) {
   // do your stuff
}

Note: I recommend you to use parametrized statements which provide much more safer dealing with database, are more human-readable and efficient.

Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106