5

I use the following batch file to create a new database in PostgreSQL 10.

echo off
cd "C:\Program Files (x86)\PostgreSQL\10\bin"
createdb -h localhost -p 5432 -U postgres myDB

But it asks to enter the password. How to prevent asking for the password? I tried the -w option explained in this link to not ask for password prompt. But this did not work. How to prevent asking for password?

2
  • I tried the pgpass file method but it did not work. But how does "manage pg_hba.conf" file method work?
    – Codename K
    Jun 8, 2018 at 21:20
  • 1
    The pgpass file solution does work. See also here and here
    – user1822
    Jun 8, 2018 at 21:38

3 Answers 3

11

use the PGPASSWORD environment variable,

@SET PGPASSWORD=something_secret
psql -c "CREATE DATABASE mydb" -U postgres postgres

or just use a connection string

psql -c "CREATE DATABASE mydb" "user=postgres dbname=postgres password=something_secret"
4
  • 2
    I see that you have given two database names, mydb and postgres (dbname=postgres). Does this mean the database mydb comes under postgres?
    – Codename K
    Jun 9, 2018 at 16:34
  • 3
    @CodenameK: to create a database (mydb) you must first be connected to another database (postgres in the above example). It does not imply a hierarchy of databases. Jun 9, 2018 at 18:20
  • Here we can read about PGPASSWORD: "Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using a password file". Aug 2 at 22:13
  • true: service or password files are a more secure solution - postgresql.org/docs/15/libpq-pgpass.html and postgresql.org/docs/15/libpq-pgservice.html
    – Jasen
    Aug 3 at 2:29
1

You may enter this line in the pg_hba.conf file like this:

# TYPE DATABASE USER ADDRESS METHOD local all postgres peer

This is for running commands from the machine. This passwordless login from local computers only If you are on Windows any user can put a switch -U postgres and connect to the machine as superuser. Do that only for development purposes.

3
1

Your problem is that you are using TCP connection and not socket connection.

I just tried on Windows 7 this command and work normally: createdb -U postgres test I hope that you notice that there is no -h localhost Since -p 5432 is default you can omit that also. I checked that pg_hba.conf doesn't have the configuration using peer but it works anyway.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.