如何将一个SQL命令文件导入PostgreSQL?

问题描述 投票:0回答:2

我在Windows 8.1上从PostgreSQL 9.4运行此命令:

psql -d dbname -f filenameincurrentdirectory.sql

例如,sql文件具有以下命令:

INSERT INTO general_lookups ("name", "old_id") VALUES ('Open',  1);
INSERT INTO general_lookups ("name", "old_id") VALUES ('Closed', 2);`

当我运行psql命令时,我收到此错误消息:

psql:filenameincurrentdirectory.sql:1: ERROR:  syntax error at or near "ÿ_I0811a2h1"
LINE 1: ÿ_I0811a2h1 ru

如何使用psql导入SQL命令文件?我在执行这些sql文件时使用pgAdmin没有问题。

windows postgresql psql byte-order-mark
2个回答
2
投票

如果您的问题是BOM,字节订单标记,则另一个选项是sed。也很好,因为如果BOM不是您的问题,它对您的数据是非破坏性的。下载并安装sed for windows:

http://gnuwin32.sourceforge.net/packages/sed.htm

名为“Complete packages,sources除外”的包中包含“Binaries”包所不包含的其他必需库。

安装sed后,运行此命令以从文件中删除BOM:

sed -i '1 s/^\xef\xbb\xbf//' filenameincurrentdirectory.sql

如果您的文件对于Notepad ++而言太大,则特别有用


0
投票

好的,问题确实与BOM,字节顺序标记有关。该文件由Microsoft Access生成。我在记事本中打开文件并将其保存为UTF-8而不是Unicode,因为Windows默认保存UTF-16。这得到了这个错误消息:psql:filenameincurrentdirectory.sql:1: ERROR: syntax error at or near "INSERT" LINE 1: INSERT INTO general_lookups ("name", "old_id" ) VAL...

然后我从另一个website那里了解到Postgres没有使用BOM,并且记事本不允许用户在没有BOM的情况下保存。因此,我必须下载Notepad ++,将编码设置为UTF-8而不使用BOM,保存文件,然后导入它。瞧!

使用Notepad ++的另一种方法是我编写的这个小python脚本。只需传入文件名即可进行转换。

import sys

if len(sys.argv) == 2:
    with open(sys.argv[1], 'rb') as source_file:
        contents = source_file.read()

    with open(sys.argv[1], 'wb') as dest_file:
        dest_file.write(contents.decode('utf-16').encode('utf-8'))
else:
    print "Please pass in a single file name to convert."
© www.soinside.com 2019 - 2024. All rights reserved.