我有一些.sql文件,其中有数千条INSERT语句,需要在我的PostgreSQL数据库上运行这些INSERT,以便将它们添加到表中。这些文件太大了,不可能打开它们并将INSERT语句复制到编辑器窗口中并在那里运行。我在网上发现,你可以通过导航到PostgreSQL安装的bin文件夹来使用以下方法:

psql -d myDataBase -a -f myInsertFile

在我的例子中:

psql -d HIGHWAYS -a -f CLUSTER_1000M.sql

然后我被要求为我的用户输入密码,但我不能输入任何东西,当我按enter键时,我得到这个错误:

psql: FATAL:密码验证失败的用户“myUsername”

为什么它不让我输入密码。是否有一种方法,因为它是至关重要的,我可以运行这些脚本?

我通过在pg_hba.conf文件中添加如下结构的新条目来解决这个问题:

# IPv6 local connections:
host    myDbName    myUserName ::1/128    trust

pg_hba.conf文件通常可以在PostgreSQL安装的'data'文件夹中找到。


当前回答

你甚至可以这样做:

sudo -u postgres psql -d myDataBase -a -f myInsertFile

如果您在机器上有sudo访问权限,并且不建议将它用于生产脚本,只用于在您自己的机器上测试,这是最简单的方法。

其他回答

你甚至可以这样做:

sudo -u postgres psql -d myDataBase -a -f myInsertFile

如果您在机器上有sudo访问权限,并且不建议将它用于生产脚本,只用于在您自己的机器上测试,这是最简单的方法。

export PGPASSWORD=<password>
psql -h <host> -d <database> -U <user_name> -p <port> -a -w -f <file>.sql

如果您在Linux shell上登录psql,则命令为:

\i fileName.sql

对于绝对路径和

\ir filename.sql

用于调用psql的相对路径。

2021的解决方案

如果你的PostgreSQL数据库在你的系统本地。

psql dbname < sqldump.sql username

如果是在线托管

psql -h hostname dbname < sqldump.sql username

如果你有任何疑问或问题,请在评论中提问。

您有四种选择来提供密码:

Set the PGPASSWORD environment variable. For details see the manual: http://www.postgresql.org/docs/current/static/libpq-envars.html Use a .pgpass file to store the password. For details see the manual: http://www.postgresql.org/docs/current/static/libpq-pgpass.html Use "trust authentication" for that specific user: http://www.postgresql.org/docs/current/static/auth-methods.html#AUTH-TRUST Since PostgreSQL 9.1 you can also use a connection string: https://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-CONNSTRING