就我而言,我正在使用AWS Redshift(基于Postgres)。看来没有其他连接到数据库,但是我遇到了同样的错误。
ERROR: database "XYZ" is being accessed by other users
就我而言,似乎数据库集群仍在对数据库进行某些处理,并且尽管没有其他外部/用户连接,但数据库仍在内部使用。我通过运行以下命令找到了它:
SELECT * FROM stv_sessions;
因此,我的技巧是在代码中编写一个循环,以查找其中包含我的数据库名称的行。(当然,循环不是无限的,而是一个困循环,等等)
SELECT * FROM stv_sessions where db_name = 'XYZ';
如果找到行,请继续删除每个PID。
SELECT pg_terminate_backend(PUT_PID_HERE);
如果找不到行,请继续删除数据库
DROP DATABASE XYZ;
注意:就我而言,我正在编写Java单元/系统测试,在这里可以认为这是可以接受的。这对于生产代码是不可接受的。
这是Java中的完整技巧(忽略我的测试/实用程序类)。
int i = 0;
while (i < 10) {
try {
i++;
logStandardOut("First try to delete session PIDs, before dropping the DB");
String getSessionPIDs = String.format("SELECT stv_sessions.process, stv_sessions.* FROM stv_sessions where db_name = '%s'", dbNameToReset);
ResultSet resultSet = databaseConnection.execQuery(getSessionPIDs);
while (resultSet.next()) {
int sessionPID = resultSet.getInt(1);
logStandardOut("killPID: %s", sessionPID);
String killSessionPID = String.format("select pg_terminate_backend(%s)", sessionPID);
try {
databaseConnection.execQuery(killSessionPID);
} catch (DatabaseException dbEx) {
//This is most commonly when a session PID is transient, where it ended between my query and kill lines
logStandardOut("Ignore it, you did your best: %s, %s", dbEx.getMessage(), dbEx.getCause());
}
}
//Drop the DB now
String dropDbSQL = String.format("DROP DATABASE %s", dbNameToReset);
logStandardOut(dropDbSQL);
databaseConnection.execStatement(dropDbSQL);
break;
} catch (MissingDatabaseException ex) {
//ignore, if the DB was not there (to be dropped)
logStandardOut(ex.getMessage());
break;
} catch (Exception ex) {
logStandardOut("Something went wrong, sleeping for a bit: %s, %s", ex.getMessage(), ex.getCause());
sleepMilliSec(1000);
}
}
GRANT CONNECT ON DATABASE thedb TO public;