Search code examples
postgresqlcommand-linepsql

How to run in-line SQL script in the command line?


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?


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
    

    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.