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?

Paul White
  • 83,961
  • 28
  • 402
  • 634
Codename K
  • 199
  • 3
  • 8

3 Answers3

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"
Jasen
  • 3,563
  • 1
  • 13
  • 17
  • 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 09 '18 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. – Daniel Vérité Jun 09 '18 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". – Boolean_Type Aug 02 '23 at 22:13
  • true: service or password files are a more secure solution - https://www.postgresql.org/docs/15/libpq-pgpass.html and https://www.postgresql.org/docs/15/libpq-pgservice.html – Jasen Aug 03 '23 at 02: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.

Mladen Uzelac
  • 829
  • 5
  • 8
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.

Mladen Uzelac
  • 829
  • 5
  • 8