我想优化此SQL查询的性能。如果我使用一百万个密钥填充此哈希表,则查询将花费大约一分钟。我如何优化这种Java方法以加快执行速度?
private HashMap<String, Boolean> selectedIds = new HashMap<>();
public void deleteSelectedIDs() throws SQLException {
if (ds == null) {
throw new SQLException();
}
Connection conn = ds.getConnection();
if (conn == null) {
throw new SQLException();
}
PreparedStatement ps = null;
ResultSet resultSet = null;
try {
conn.setAutoCommit(false);
boolean committed = false;
try {
String sqlDeleteQuery = "DELETE FROM ACTIVESESSIONSLOG WHERE ASESSIONID = ?";
Set<String> keySet = selectedIds.keySet();
String[] keys = new String[]{};
keys = selectedIds.keySet().toArray(keys);
ps = conn.prepareStatement(sqlDeleteQuery);
for (int i = 0; i < keys.length; i++) {
if (selectedIds.get(keys[i]).booleanValue()) {
ps.setString(1, keys[i]);
ps.executeUpdate();
ps.clearParameters();
selectedIds.put(keys[i], false); //get(keys[i]) = false;
}
}
conn.commit();
committed = true;
//selectedIds.clear();
} finally {
if (!committed) {
conn.rollback();
}
}
} finally {
ps.close();
conn.close();
}
}
答案 0 :(得分:5)
如果您的JDBC驱动程序支持它,请使用batch processing。它易于使用,并且在这种情况下往往效果很好。
答案 1 :(得分:3)
有人可能有更好的想法,但您是否考虑过通过临时表将密钥列表传递给Oracle,然后在PL / SQL函数中执行循环。它会降低流量,DB会进行处理。
答案 2 :(得分:2)
创建一个临时表并将所有ID插入其中。然后对临时表中的那些进行单个删除。
答案 3 :(得分:2)
我认为最好使用CallableStatement和oracle procedure。
代码段
SQL> create type temp_tbl
2 is
3 table of number;
4 /
...
SQL> create or replace procedure stored_p
2 (
3 list in temp_tbl,
4 p_rc out sys_refcursor )
5 as
6 begin
7 open
8 p_rc for delete from ACTIVESESSIONSLOG where ASESSIONID
in (select * from table(list));
9 end;
10 /