【发布时间】:2015-03-15 16:20:20
【问题描述】:
我正在使用 jdbc 连接到数据库并获取多行作为 ResultSet 的一部分。我从 ResultSet 运行了一个 sql,但不知何故最终只通过了第一行。例如:query1 是我生成两个 pid 行的结果集。然后我使用 query2 来终止 pid。我希望 query2 遍历 query1 中的所有行并一个接一个地执行终止命令。需要注意的另一点是 query1 可以有超过 2 行,具体取决于结果集。以下是我正在使用的代码,不胜感激。顺便说一句,我确实尝试在 while 中使用嵌套的 for 循环,并且不会像我在数据库日志中看到的那样重新发出 query2。
Statement stmt = connection.createStatement();
ResultSet res = stmt.executeQuery(
"SELECT \n" +
"kl.pid as blocking_pid,\n" +
"ka.usename as blocking_user,\n" +
"ka.query as blocking_query,\n" +
"bl.pid as blocked_pid,\n" +
"a.usename as blocked_user, \n" +
"a.query as blocked_query, \n" +
"to_char(age(now(), a.query_start),'HH24h:MIm:SSs') as age\n" +
"FROM pg_catalog.pg_locks bl\n" +
"JOIN pg_catalog.pg_stat_activity a \n" +
"ON bl.pid = a.pid\n" +
"JOIN pg_catalog.pg_locks kl \n" +
"ON bl.locktype = kl.locktype\n" +
"and bl.database is not distinct from kl.database\n" +
"and bl.relation is not distinct from kl.relation\n" +
"and bl.page is not distinct from kl.page\n" +
"and bl.tuple is not distinct from kl.tuple\n" +
"and bl.virtualxid is not distinct from kl.virtualxid\n" +
"and bl.transactionid is not distinct from kl.transactionid\n" +
"and bl.classid is not distinct from kl.classid\n" +
"and bl.objid is not distinct from kl.objid\n" +
"and bl.objsubid is not distinct from kl.objsubid\n" +
"and bl.pid <> kl.pid \n" +
"JOIN pg_catalog.pg_stat_activity ka \n" +
"ON kl.pid = ka.pid\n" +
"WHERE kl.granted and not bl.granted\n" +
"ORDER BY a.query_start");
//Get all the blocking pids and run pg_terminate_backend
while (res.next()) {
String pid = res.getString("blocking_pid");
stmt.execute("SELECT pg_terminate_backend(" + String.valueOf(pid) + ")");
}
stmt.close();
connection.close();
【问题讨论】: