Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute postgres' sql queries from batch file?

I need to execute SQL from batch file. I am executing following to connect to Postgres and select data from table

C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME% 
select * from test;

I am able to connect to database, however I'm getting the error

'select' is not recognized as an internal or external command, operable program or batch file.

Has anyone faced such issue?

This is one of the query i am trying, something similar works in shell script, (please ignore syntax error in the query if there are any)

copy testdata (col1,col2,col3) from '%filepath%/%csv_file%' with csv;
like image 312
Ketu Avatar asked Jan 19 '16 15:01

Ketu


1 Answers

Use the -f parameter to pass the batch file name

C:/pgsql/bin/psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME% -f 'sql_batch_file.sql'

http://www.postgresql.org/docs/current/static/app-psql.html

-f filename

--file=filename

Use the file filename as the source of commands instead of reading commands interactively. After the file is processed, psql terminates. This is in many ways equivalent to the meta-command \i.

If filename is - (hyphen), then standard input is read until an EOF indication or \q meta-command. Note however that Readline is not used in this case (much as if -n had been specified).

like image 88
Clodoaldo Neto Avatar answered Sep 25 '22 11:09

Clodoaldo Neto