postgresql 如何为 postgres 连接设置 application_name?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30322206/
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-10-21 01:54:53  来源:igfitidea点击:

How to set application_name for postgres connections?

javapostgresqlconnection-poolingtomcat-jdbc

提问by membersound

I'm using tomcat connection pool org.apache.tomcat.jdbc.pool.DataSource. The connections appear in my database pg_stat_activitywith empty application_name.

我正在使用 tomcat 连接池org.apache.tomcat.jdbc.pool.DataSource。连接出现在我的数据库中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 应用程序中设置该应用程序名称,以便我知道每个连接的来源(因为将有多个应用程序访问同一个数据库)?

采纳答案by Cristian Sevescu

You could specify the application name in the connection string.
Documentation here.

您可以在连接字符串中指定应用程序名称。
文档在这里

Example:

例子:

jdbc:postgresql://localhost:5435/DBNAME?ApplicationName=MyApp

Take care: the param names are case sensitive.

注意:参数名称区分大小写。

回答by klin

Use set command:

使用设置命令:

set application_name to my_application;

回答by Mike

If you want to set programmatically, the PostgreSQL drivers also have a method you can call:

如果要以编程方式进行设置,PostgreSQL 驱动程序也有一个可以调用的方法:

PGPoolingDataSource ds = new PGPoolingDataSource();
ds.setApplicationName(applicationName);

回答by a_horse_with_no_name

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 e.g. to reflect different modules insideyour application, the you can use the SETcommand as shown by klin.

如果你想改变它动态地如以反映不同的模块里面你的应用程序时,您可以使用SET命令如图克林。

回答by ??????? ????

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")