How to execute postgres' sql queries from batch file?

后端 未结 7 1526
小蘑菇
小蘑菇 2021-02-08 14:36

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_         


        
相关标签:
7条回答
  • 2021-02-08 15:10

    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.

    0 讨论(0)
  • 2021-02-08 15:10

    If you are trying the shell script

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

    0 讨论(0)
  • 2021-02-08 15:10

    if running on Linux, this is what worked for me (need to update values below with your user, db name etc)

    psql "host=YOUR_HOST port=YOUR_PORT dbname=YOUR_DB_NAME user=YOUR_USER_NAME password=YOUR_PASSWORD" -f "fully_qualified_path_to_your_script.sql"
    
    0 讨论(0)
  • 2021-02-08 15:16

    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%
    
    0 讨论(0)
  • 2021-02-08 15:20

    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

    0 讨论(0)
  • 2021-02-08 15:28

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

    0 讨论(0)
提交回复
热议问题