[英]How to set application_name for postgres connections?
I'm using tomcat connection pool org.apache.tomcat.jdbc.pool.DataSource
.我正在使用 tomcat 连接池org.apache.tomcat.jdbc.pool.DataSource
。 The connections appear in my database pg_stat_activity
with empty application_name
.连接出现在我的数据库pg_stat_activity
中,且application_name
为空。
How could I set that application name in my java app, so I know where each connection comes from (as there will be multiple applications accessing the same db)?如何在我的 java 应用程序中设置该应用程序名称,以便我知道每个连接来自哪里(因为将有多个应用程序访问同一个数据库)?
使用设置命令:
set application_name to my_application;
You can add this to the JDBC URL that you use in your connection pool definition:您可以将其添加到您在连接池定义中使用的 JDBC URL:
jdbc:postgresql://localhost/postgres?ApplicationName=my_app
If you want to change it dynamically eg to reflect different modules inside your application, the you can use the SET
command as shown by klin.如果您想动态更改它,例如反映应用程序中的不同模块,您可以使用 klin 所示的SET
命令。
If you want to set programmatically, the PostgreSQL drivers also have a method you can call:如果您想以编程方式设置,PostgreSQL 驱动程序也有一个您可以调用的方法:
PGPoolingDataSource ds = new PGPoolingDataSource();
ds.setApplicationName(applicationName);
对于那些使用普通连接字符串而不是 jdbc 的人:
postgresql://other@localhost/otherdb?application_name=myapp
If you're using Python library psycopg2
, here's how you can do如果您使用的是 Python 库psycopg2
,那么您可以这样做
import psycopg2
psycopg2.connect(host=host_ip, database=db_name, user=user, password=db_pwd, application_name="Python Local Test Script")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.