postgresql 如何在命令行中运行内嵌 SQL 脚本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22824457/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to run in-line SQL script in the command line?
提问by zs2020
I have trouble to execute a SQL script via command line, this is what I have
我无法通过命令行执行 SQL 脚本,这就是我所拥有的
"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.
我在 Windows 7 上使用 Postgresql 9.3。
Any idea how to do that?
知道怎么做吗?
回答by Erwin Brandstetter
You must connect to a databaseto run a command, even if you want to run CREATE DATABASE
, so:
您必须连接到数据库才能运行命令,即使您想运行CREATE DATABASE
,所以:
"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.
(正如@Craig 澄清的那样,对于 Windows,它必须是双引号。)
在postgres
此处使用默认维护数据库。
There is a better option for the purpose at hand, though: createdbfrom the command-line directly.
还有为宗旨就在眼前,但一个更好的选择:CREATEDB从命令行直接。
回答by Craig Ringer
Windows's cmd.exe
expects double quotes on arguments, not single quotes.
Windowscmd.exe
期望参数上有双引号,而不是单引号。
"CREATE DATABASE test;"
http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx
http://blogs.msdn.com/b/oldnewthing/archive/2010/09/17/10063629.aspx
回答by Vinish George
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.3\bin\psql.exe" -h %server% -U %username% -d %database% -p %port% -c %query%
pause