40

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

6 Answers 6

48

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

Example:

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

Take care: the param names are case sensitive. [1]: https://jdbc.postgresql.org/documentation/use/

Sign up to request clarification or add additional context in comments.

1 Comment

@Gajus: I think that's only for libpq. JDBC still uses ApplicationName, it seems
28

Use set command:

set application_name to my_application;

Comments

11

For those using normal connection string and not jdbc:

postgresql://other@localhost/otherdb?application_name=myapp

2 Comments

if that's normal, what is the form with spaces?
8

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.

Comments

4

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

Comments

3

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.