0

Can I include the password to my psql command?

My command is:

psql -h localhost -p 5432 -U mee -d my_db -f sqltest.sql

because I'm trying to run it through my java application but i didn't know how to specify it.

Process pro = Runtime.getRuntime().exec("psql -h localhost -p 5432 -U mee -d my_db -f sqltest.sql");

BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream()));
String line;
while ((line = br.readLine()) != null)
      System.out.println("heeeeeeeeeeere : "+line);
4
  • Well, did you take a look at the psql documentation? Commented Jul 20, 2017 at 9:25
  • yes. I found that -W force the user to insert the password, but i diddn't really get the point of -w. should I insert the password in pgpass file so i will not be obliged to insert it in the cmd? Commented Jul 20, 2017 at 9:45
  • 2
    Well, not thoroughly enough. There is the possibility of passing password through an environment variable, or through a connection string (instead of database name), or, as the answer mentions, using .pgpass. All of this information is reachable through the documentation. Commented Jul 20, 2017 at 11:04
  • 1
    If you do not want to store the password outside of your application: Connection URIs. For example: psql -d 'postgresql://mee:secretpassword@localhost:5432/my_db' -f sqltest.sql Commented Jul 20, 2017 at 12:07

1 Answer 1

2

The most you can do is save the password for the user you are connecting through in .pgpass file - located in a user's home directory. This way psql will not ask for the password. There is no way to pass password as an argument with psql.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.