How to execute postgres' sql queries from batch file?

家住魔仙堡 提交于 2019-12-21 04:34:10

问题


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;

回答1:


You could pipe it into psql

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

When closing parenthesis are part of the SQL query they have to be escaped with three carets.

( 
echo insert into testconfig(testid,scenarioid,testname ^^^) values( 1,1,'asdf'^^^);
) | psql -h %DB_HOST% -p 5432 -U %DB_USER% -d %DB_NAME%



回答2:


I agree with Spidey:

1] if you are passing the file with the sql use -f or --file parameter

When you want to execute several commands the best way to do that is to add parameter -f, and after that just type path to your file without any " or ' marks (relative paths works also):

psql -h %host% -p 5432 -U %user% -d %dbname% -f ..\..\folder\Data.txt

It also works in .NET Core. I need it to add basic data to my database after migrations.




回答3:


You cannot put the query on separate line, batch interpreter will assume it's another command instead of a query for psql. I believe you will need to quote it as well.




回答4:


Kindly refer to the documentation

1] if you are passing the file with the sql use -f or --file parameter
2] if you are passing individual command use -c or --command parameter




回答5:


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).




回答6:


If you are trying the shell script

psql postgresql://$username:$password@$host/$database < /app/sql_script/script.sql



来源:https://stackoverflow.com/questions/34880453/how-to-execute-postgres-sql-queries-from-batch-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!