Antag user_id
er en long
.
PreparedStatement psUserLocation = conB.prepareStatement("SELECT location FROM B.users WHERE user_id = ?");
while(rs.next()) {
//call select statement for database B to get the location for each user id
long userId = rs.getLong(user_id);
psUserLocation.setLong(1, userId)
ResultSet userLocation = ps.executeQuery();
// Do whatever with the location(s)
}
REDIGER :én forespørgsel for alle brugere i stedet for én forespørgsel pr. bruger:
private final static String QUERY = "SELECT user_id, location FROM B.users WHERE user_id IN (%a)";
StringBuilder userList = new StringBuilder();
while(rs.next()) {
long userId = rs.getLong(user_id);
userList.append(userId);
if (!rs.isLast()) {
userList.append(",");
}
}
String usersLocationQuery = QUERY.replaceAll("%a", userList.toString());
PreparedStatement psUsersLocation = conB.prepareStatement(usersLocationQuery);
ResultSet usersLocation = psUsersLocation.executeQuery();
// Do whatever with the locations
Husk, at dette kan fejle/fungere forkert, fordi de fleste DB har en grænse for, hvor mange elementer en SQL IN
klausul kan indeholde. Også denne anden metode kan tillade en SQL-injektion på %a
udskiftning.