32

I'm using tomcat connection pool org.apache.tomcat.jdbc.pool.DataSource. The connections appear in my database pg_stat_activity with empty 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)?

membersound
  • 81,582
  • 193
  • 585
  • 1,120

6 Answers6

37

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.

Cristian Sevescu
  • 1,364
  • 8
  • 11
26

Use set command:

set application_name to my_application;
klin
  • 112,967
  • 15
  • 204
  • 232
7

You can add this to the JDBC URL that you use in your connection pool definition:

jdbc:postgresql://localhost/postgres?ApplicationName=my_app

If you want to change it dynamically e.g. to reflect different modules inside your application, the you can use the SET command as shown by klin.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
7

For those using normal connection string and not jdbc:

postgresql://other@localhost/otherdb?application_name=myapp
Matteo
  • 2,256
  • 26
  • 42
3

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

PGPoolingDataSource ds = new PGPoolingDataSource();
ds.setApplicationName(applicationName);
Mike
  • 4,722
  • 1
  • 27
  • 40
3

If you're using Python library psycopg2, here's how you can do

import psycopg2    
psycopg2.connect(host=host_ip, database=db_name, user=user, password=db_pwd, application_name="Python Local Test Script")
Krishna
  • 6,107
  • 2
  • 40
  • 43