Question

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?

Était-ce utile?

La solution

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

(As @Craig cleared up, it must be double quotes for Windows.)
Using the default maintenance db postgres here.

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

Autres conseils

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

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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top