0

我正在尝试在一个字符串中获取选择查询。这就是我要的。我尝试了不同的方法,但无法解决。这是我的代码:

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();

我这样做了,但是有错误。我该如何解决?基本上,我想在一个字符串中添加许多查询,然后执行该字符串。然后我需要它们在结果集之类的东西中。

4

1 回答 1

2

我对你想要达到的目标有点困惑,但我想你需要这个:

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

然后你只需要执行这一个查询,你就会得到想要的结果。

但也正如@dystroy 提到的,如果您想使用您的方法,您首先需要从 User 获取 id 到 some中List<Integer>,然后创建一些List<String>将在您的查询中保存您的查询或 useIN子句的方法。

伪代码:

// 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
}

注意:我建议您使用参数化的语句,这样可以更安全地处理数据库,更易于阅读和更高效。

于 2013-05-14T15:21:02.643 回答