java - jdbc - how to select query in one string -
i trying fetch select queries in 1 string. want. tried different ways, not solve. code:
resultset rs = st.executequery("select city_id user name = '" + name + "'"); string sql = ""; while (rs.next()) { sql += "select * city id = " +rs.getint(1) + ","; } sql = sql.substring(0, sql.length()-1); preparedstatement stmt = con.preparestatement(sql); rs = stmt.executequery();
i did this, there errors. how can solve it? basically, want add many queries in 1 string, , execute string. need them in resultset.
i'm little confused trying achieve guess need this:
select * city c inner join user u on (c.id = u.city_id) u.name = ?;
then need execute 1 query , have desired results.
but @dystroy mentioned if want use approach need @ first fetch ids user list<integer>
, create list<string>
hold queries or use in
clause in query.
pseudo-code:
// getting ids user list<integer> cityids = new arraylist<integer>(); string query = "select city_id user 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 query stringbuilder builder = new stringbuilder("select * city id in ("); (int = 0; < cityids.size(); i++) { builder.append("?"); if (i < cityids.size() - 1) { builder.append(","); } } builder.append(")"); // creating preparedstatement ps = con.preparestatement(builder.tostring()); // adding params query int index = 1; (integer id: cityids) { ps.setint(index, id); index++; } resultset rs = ps.executequery(); while (rs.next()) { // stuff }
note: recommend use parametrized statements provide more safer dealing database, more human-readable , efficient.
Comments
Post a Comment