SQL 如何在 PostgreSQL 上列出活动连接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27435839/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 03:03:09  来源:igfitidea点击:

How to list active connections on PostgreSQL?

sqlpostgresqldatabase-connectionlistings

提问by Tregoreg

Is there a command in PostgreSQL to select active connections to a given database?

PostgreSQL 中是否有一个命令可以选择到给定数据库的活动连接?

psqlstates that I can't drop one of my databases because there are active connections to it, so I would like to see what the connections are (and from which machines)

psql声明我不能删除我的数据库之一,因为有活动连接到它,所以我想看看连接是什么(以及来自哪些机器)

回答by Tregoreg

Oh, I just found that command on PostgreSQL forum:

哦,我刚刚在 PostgreSQL 论坛上找到了这个命令:

SELECT * FROM pg_stat_activity;

回答by Neeraj Bansal

Following will give you active connections/ queries in postgres DB-

以下将为您提供 postgres DB 中的活动连接/查询-

SELECT 
    pid
    ,datname
    ,usename
    ,application_name
    ,client_hostname
    ,client_port
    ,backend_start
    ,query_start
    ,query
    ,state
FROM pg_stat_activity
WHERE state = 'active';

You may use 'idle' instead of active to get already executed connections/queries.

您可以使用 'idle' 而不是 active 来获取已执行的连接/查询。

回答by Abdollah

SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';

Since pg_stat_activitycontains connection statistics of all databases having any state, either idleor active, database name and connection state should be included in the query to get the desired output.

由于pg_stat_activity包含具有任何状态的所有数据库的连接统计信息,因此应在查询中包含idleactive、数据库名称和连接状态以获得所需的输出。