8

I have trouble to execute a SQL script via command line, this is what I have

"C:\..\psql.exe" -h my_server_host -U username -c 'CREATE DATABASE test;'

I got this error:

psql: warning: extra command-line argument "test;'" ignored
psql: FATAL:  database "DATABASE" does not exist

I am on Windows 7 with Postgresql 9.3.

Any idea how to do that?

1
  • 1
    You should mention your OS and your version of Postgres here. Commented Apr 2, 2014 at 22:55

3 Answers 3

15

You must connect to a database to run a command, even if you want to run CREATE DATABASE, so:

"C:\..\psql.exe" -h my_server_host -U usr -c 'CREATE DATABASE test;' postgres

Double quotes for Windows, as Craig provided: ... "CREATE DATABASE test;" ...
Connecting to the default maintenance DB postgres here.

There is a better option for the purpose at hand, though: createdb from the command-line directly.

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

1 Comment

Thanks. Your point is correct. And I need to use double quotes instead as mentioned by Craig Ringer.
1

Windows's cmd.exe expects double quotes on arguments, not single quotes.

"CREATE DATABASE test;"

http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx

2 Comments

I got this error "psql: FATAL: database "<username>" does not exist", <username> is the username I passed in and it seems the command picked the username as the database name
Yes, it does by default. If you want a different DB name, specify it on the command line with the -d flag. See the manual for the psql command.
1

Use the following script to execute the query:

@echo off
SET server=my_server_host
SET database=my_db_name
SET port=my_db_port
SET username=my_user_name
SET query="CREATE DATABASE test;"
for /f "delims=" %%a in ('chcp ^|find /c "932"') do @ SET CLIENTENCODING_JP=%%a
if "%CLIENTENCODING_JP%"=="1" SET PGCLIENTENCODING=SJIS
if "%CLIENTENCODING_JP%"=="1" SET /P PGCLIENTENCODING="Client Encoding [%PGCLIENTENCODING%]: "
REM Run psql
"C:\Program Files\PostgreSQL\9.3\bin\psql.exe" -h %server% -U %username% -d %database% -p %port%  -c %query%
pause

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.