我有以下代码非常简单但如果我正在迭代的地图有很多条目,那么显然会慢得令人无法接受。
public Map<String, String> getIdToEmailMapping(Connection conn, Map<String, String> map) {
Map<String, String> id_email_map = new HashMap<String, String>();
try {
PreparedStatement stmt = null;
String sql = "SELECT EMAIL FROM DATA_VIEW WHERE URL=?";
stmt = conn.prepareStatement(sql);
for (Map.Entry<String, String> entry : map.entrySet()) {
stmt.setString(1, entry.getValue()); // set URL in sql statement
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
String email = rs.getString("EMAIL");
String id = entry.getKey();
id_email_map.put(id, email);
}
rs.close();
}
stmt.close();
} catch (SQLException se) {
se.printStackTrace();
}
return id_email_map;
}
我希望地图有数千个条目,所以这个实现很糟糕......但我不确定我是否可以通过其他任何方式进行。我尝试搜索这类问题的任何SQL技巧,但我找不到任何东西。有没有人有任何想法?
答案 0 :(得分:0)
也许是这样的:
static void call(final Connection con) throws SQLException {
Map<String, String> emailMap = new HashMap<>();
emailMap.put("id1", "someVal");
emailMap.put("id2", "someVal");
emailMap.put("id3", "someVal");
emailMap.put("id4", "someVal");
String collect = emailMap.keySet().stream().collect(Collectors.joining(","));
String query = " SELECT EMAIL FROM DATA_VIEW WHERE URL IN (" + collect + ")";
try (Statement s = con.createStatement()) {
ResultSet executeQuery = s.executeQuery(query);
// do your result processing
}
}
您可以针对所有ID或网址发送一个查询,而不是单独查询所有网址。查询将如下所示:
SELECT EMAIL FROM DATA_VIEW WHERE URL in (id2,id1,id4,id3)
希望有所帮助。