How to create a new database in PostgreSQL 10 in Windows from batch file?

Posted on

Question :

I am creating a batch file to create a new database in PostgreSQL 10. I used the following code,

echo off
cd "C:Program Files (x86)PostgreSQL10bin"
psql "dbname=myDB host=localhost user=postgres password=postgres port=5432"

But I get this error,

psql: FATAL: database “myDB” does not exist

I understand this is not the command to create a new database. I also tried the following code,

echo off
cd "C:Program Files (x86)PostgreSQL10bin"
psql "createdb myDB passfile %APPDATA%postgresqlpgpass.conf"

This is based on the information in this link. The “pgpass.conf” file has the follwoing text,


But it asks to enter password. I entered the default password “postgres”. But this was the output,

psql: FATAL: password authentication failed for user “User1”

The objective here is to create new database from the batch file without asking for password. How to achieve this?

Answer :

Create a bat file with the following content and execute it:

c:pathtopostgresqlbinpsql.exe -f C:pathtodb_create.sql  postgresql://user:password@localhost:port/postgres

This is what worked for me.

Other way to work for me is:

1.- Create one test.bat file with this content:

@set PGPASSFILE=D:bashTest02.conf
@"C:Program FilesPostgreSQL12bin"createdb -U postgres PEDIDOS-2052021141847

Leave a Reply

Your email address will not be published. Required fields are marked *