Команда postgres psql не распознается в среде windows

For Postgres, I keep getting this error multiple times even though I have already set the location of the bin folder to the path variable in Windows 8. Is there something else I'm missing? (I can'...

For Postgres, I keep getting this error multiple times even though I have already set the location of the bin folder to the path variable in Windows 8. Is there something else I’m missing?

(I can’t post pictures since I don’t have enough reputation)

a_horse_with_no_name's user avatar

asked May 22, 2015 at 16:15

as1216's user avatar

5

Just an update because I was trying it on Windows 10 you do need to set the path to the following:
;C:Program FilesPostgreSQL14bin ;C:Program FilesPostgreSQL9.5lib

PS : 14 is the current version, check whatever version you are on.
You can do that either through the CMD by using set PATH [the path]
or from my

computer => properties => advanced system settings=> Environment
Variables => System Variables

Then search for path.

Important: don’t replace the PATHs that are already there just add one beside them as follows ;C:Program FilesPostgreSQL9.5bin ;C:Program FilesPostgreSQL9.5lib

Please note: On windows 10, if you follow this: computer => properties => advanced system settings=> Environment Variables => System Variables> select PATH, you actually get the option to add new row. Click Edit, add the /bin and /lib folder locations and save changes.

Then close your command prompt if it’s open and then start it again
try psql —version
If it gives you an answer then you are good to go if not try echo %PATH% and see if the path you set was added or not and if it’s added is it added correctly or not.

Important note:

Replace 9.5 with your current version number. As of 2021, that is 13.
For 2022 is 14.

answered Jul 10, 2016 at 20:50

Shahin's user avatar

ShahinShahin

2,3131 gold badge12 silver badges16 bronze badges

2

Windows 10

It could be that your server doesn’t start automatically on windows 10 and you need to start it yourself after setting your Postgresql path using the following command in cmd:

pg_ctl -D "C:Program FilesPostgreSQL11.4data" start

You need to be inside «C:Program FilesPostgreSQL11.4bin» directory to execute the above command.

EX:

enter image description here

You still need to be inside the bin directory to work with psql

answered Jul 18, 2019 at 18:17

Abdel-Raouf's user avatar

Abdel-RaoufAbdel-Raouf

6701 gold badge7 silver badges20 bronze badges

Enter this path in your System environment variable.

C:Program FilesPostgreSQL[YOUR PG VERSION]bin

In this case i’m using version 10. If you check the postgres folder you are going to see your current versions.

In my own case i used the following on separate lines:

C:Program FilesPostgreSQL10bin
C:Program FilesPostgreSQL10lib

answered Jan 16, 2020 at 13:34

Divine Hycenth's user avatar

1

I had your issue and got it working again (on windows 7).

My setup had actually worked at first. I installed postgres and then set up the system PATH variables with C:Program FilesPostgreSQL9.6bin; C:Program FilesPostgreSQL9.6lib. The psql keyword in the command line gave no errors.

I deleted the PATH variables above one at a time to test if they were both really needed. Psql continued to work after I deleted the lib path, but stopped working after I deleted the bin path. When I returned bin, it still didn’t work, and the same with lib. I closed and reopened the command line between tries, and checked the path. The problem lingered even though the path was identical to how it had been when working. I re-pasted it.

I uninstalled and reinstalled postgres. The problem lingered. It finally worked after I deleted the spaces between the «; C:…» in the paths and re-saved.

Not sure if it was really the spaces that were the culprit. Maybe the environment variables just needed to be altered and refreshed after the install.

I’m also still not sure if both lib and bin paths are needed since there seems to be some kind of lingering memory for old path configurations. I don’t want to test it again though.

answered Nov 27, 2016 at 9:18

voluntier's user avatar

voluntiervoluntier

2703 silver badges11 bronze badges

If you tried all the answers and still spinning your heads, don’t forget to change the version with your one which you downloaded.

For example, don’t simply copy paste

;C:Program FilesPostgreSQL9.5bin ;C:Program FilesPostgreSQL9.5lib

More clearly,

;C:Program FilesPostgreSQL[Your Version]bin ;C:Program FilesPostgreSQL[Your Version]lib

I was spinning my heads. Hope this helps.

answered Dec 13, 2018 at 4:49

creamCheeseCoder's user avatar

2

You can follow the following steps below.

C:Program FilesPostgreSQLyourversion

enter image description here
enter image description here

answered Aug 19, 2021 at 16:35

Soner from The Ottoman Empire's user avatar

Make sure that the path actually leads to the executables. I’m using version 11 and it did not work until this was set as the path:

C:Program FilesPostgreSQL11binbin

Maybe this is how version 11 is structured or I somehow botched the installation but I haven’t had a problem since.

answered Feb 13, 2019 at 4:38

Nate's user avatar

NateNate

511 silver badge1 bronze badge

Even if it is a little bit late, i solved the PATH problem by removing every space.

;C:Program FilesPostgreSQL<installed version>bin;C:Program FilesPostgreSQL<installed version>lib

works for me now.

decoder's user avatar

decoder

6342 gold badges9 silver badges18 bronze badges

answered Aug 17, 2018 at 8:34

derRichter's user avatar

derRichterderRichter

511 silver badge4 bronze badges

0

Simple solution that hasn’t been mentioned on this question: restart your computer after you declare the path variable.

I always have to restart — the path never updates until I do. And when I do restart, the path always is updated.

answered Apr 18, 2020 at 19:23

Michael Jay's user avatar

Michael JayMichael Jay

4533 silver badges11 bronze badges

Find your binaries file where it is saved. get the path in terminal mine is

C:UsersLENOVODocumentspostgresql-9.5.21-1-windows-x64-binaries (1)pgsqlbin

then find your local user data path, it is in mostly

C:usrlocalpgsqldata

now all we have to hit the following command in the binary terminal path:

C:UsersLENOVODocumentspostgresql-9.5.21-1-windows-x64-binaries (1)pgsqlbin>pg_ctl -D "C:usrlocalpgsqldata" start

done!

answered May 13, 2020 at 23:10

Anupam Maurya's user avatar

Always better to install a previous version or in the installation make sure you specify the ‘/data’ in a separate directory folder «C:data»

answered Oct 6, 2020 at 13:34

Tshiamo Motshabi's user avatar

0

For Windows 10 and 11 users, here are the steps:

  1. Go to Edit environment variables for your account (search for it on the start menu)
  2. It will open the System Properties form — click the Environment Variables
  3. Under the User variables for <username> (or you can add it in system variables), find the path variables and click edit, and add the path to your Postgres bin file address (in my case it’s C:Program FilesPostgreSQL15bin).
  4. And save it and re-open the terminal.

answered Nov 25, 2022 at 13:24

Tri Dawn's user avatar

Tri DawnTri Dawn

3903 silver badges9 bronze badges

Вопрос №22424 от пользователя Станислав Почековский в уроке «Подготовка к работе», курс «Основы реляционных баз данных»

Команда $ sudo -u postgres createuser —createdb hexletbot не работе, пользователь не создается, вообще ни какой реакции. работаю на винде, много модифицировал команду все равно не помогает.

Сработало только так: CREATE USER hexletbot WITH PASSWORD ‘fjshdedaw’ CREATEDB;

Аналогично и создание базы данных: Так сработало: CREATE DATABASE hexlet; так нет: createdb hexlet

Почему обертки не работают а только полноценные команды?

Еще есть вопросы по копированию базы данных, не совсем понял порядок действий:

  1. git clone https://github.com/hexlet-components/pg-dump-example.git
  2. cd pg-dump-example
  3. Открываем Makefile и вводим команды оттуда? db-reset schema-load data-load/ psql hexlet < schema.sql/ psql hexlet < schema.sql/ итд?

Пока результат таков (раз пример):

К сожалению по windows не подскажу. Если есть возможность, работайте с pg на маке или линуксе.

Хорошо. А по этому вопросу

Еще есть вопросы по копированию базы данных, не совсем понял порядок действий: git clone https://github.com/hexlet-components/pg-dump-example.git cd pg-dump-example Открываем Makefile и вводим команды оттуда? db-reset schema-load data-load/ psql hexlet < schema.sql/ psql hexlet < schema.sql/ итд?

Увы работать на линуксе или маке пока нет возможности. Мб сделаете пояснения для работающих на windows а то курс какой то однобокий получается.

Мб сделаете пояснения для работающих на windows а то курс какой то однобокий получается.

Мы изначально, в наших базовых курсах, говорим о том, что полноценная веб-разработка возможна только из под POSIX совместимых операционных системах, и сделали довольно много материала на тему того как их поставить настроить и использовать. Ваш продакшен все равно будет на линуксе.

Открываем Makefile и вводим команды оттуда? db-reset schema-load data-load/ psql hexlet < schema.sql/ psql hexlet < schema.sql/ итд?

https://guides.hexlet.io/ — вот здесь есть множество статей на тему как довести виндовс до линукса например через его подсистему Ubuntu или через вагрант.

Вводим те команды которые написаны в README.md

Господа, дайте же нормальные пояснение как работать с файлом Makefile. Как и в какой последовательно вводить команды оттуда, уже сколько бьюсь над этим. Подписка платная, хочется учиться а тут как квесты. а что же имел ввиду учитель. Может хоть пример реального ввода в консоль напишете.

В ридми этого репозитория ровно три строки. Вы их выполнили?

p.s. Если вы хотите чтобы ваш вопрос не потерялся, задавайте его в отдельном топике, этот топик не привязан к вашему менторингу.

Created db hexlet — сделано.

Created role with name of your system user — сделано.

cd pg-dump-example — сделано.

make # look at the Makefile — вот тут уже проблемы. как вводить команды make и далее из файла? или. полное непонимание.

make # look at the Makefile — вот тут уже проблемы. как вводить команды make и далее из файла? или. полное непонимание.

Перед вами и есть команда make , ее надо запустить и все. То что вы видите в ридми, это просто три команды подряд.

Такой результат. $ make # look at the Makefile bash: make: command not found

Какой еще вариант ставить Cygwin только? Мне нужно только чтобы терминале винды были полностью доступны команды linux.

Это значит что не установлен мейк. Его надо установить.

Оу, так вы не проходили наш курс по основам командной строки. Пройдите пожалуйста, станет сильно понятнее. Ну и git bash это не то. Вот тут рекомендации https://guides.hexlet.io/development-on-windows/

Добрый день, на windows нужно установить gnuwin32 — make for windows, потом прописать в PATH (в моем случае — C:Program Files (x86)GnuWin32bin ) и перезапустить консоль. в git-bash работает через make.exe

Спасибо за gnuwin32. Теперь после ввода make такой результат это ок?

$ make # look at the Makefile

dropdb hexlet || true

и все дальше просто ничего не происходит. При закрытии консоли вылетает окно — http://prntscr.com/m8ix3m

Апдейт. в итоге через терминал PowerShell кажется получилось, раз 5 был запрос пароля итд.

Это какие-то виндовые особенности. Лучше конечно поставить ubuntu for windows.

команда postgres «psql» не распознается в среде windows

кажется, я его настроил, у меня есть моя база данных.yml с помощью postgres, и я могу подключить базу данных с pgadmin III, но когда я попытался с помощью команды psql проверить, какая версия, она говорит, что не распознается? Есть идеи, что мне делать?

Я использую windows и использую командную строку с Ruby on Rails. Использование PostgreSQL 9.2, установленного с помощью установщика EnterpriseDB one-click.

4 ответов

предполагая, что вы установили PostgreSQL в Windows с установщиком PostgreSQL «One-click», упакованным EnterpriseDB, psql не добавляется к PATH автоматически. Это отчасти потому, что добавление его в путь может вызвать путаницу, когда у людей установлено несколько версий PostgreSQL.

вам нужно указать полный явный путь к psql , например:

или добавить psql для переменные среды, см. например этот руководство.

Открыть Командную Строку

если на строке выше не отображается версия psql, выполните следующие действия

Откройте командную строку и повторите

это потому, что между ; и ваш путь psql, поэтому он должен быть похож на *****;C:Program FilesPostgreSQL.2bin .

если есть пробел после ****** ; тогда это не сработает. Вы действительно можете ввести %PATH% в командной строке cmd и посмотреть, как ваша переменная среды и пространство выглядит. Я пробовал оба случая для вас, первый с пространством имел ту же ошибку, о которой Вы упомянули, а второй без пространства работал.

вам нужно установить как bin, так и путь lib в переменной среды PATH, разделенной точкой с запятой:

%PROGRAMFILES\%с PostgreSQL 9.2 ОГРН;%PROGRAMFILES%\с PostgreSQL 9.2Либ

Не могу установить PostgreSQL на Windows 10?

Я не могу установить PostgreSQL, сделал все по инструкции, уже три раза сносил и заново переустанавливал, инструкция НЕ РАБОТАЕТ, или устарела. Система Windows 10.

Скачал, все есть в папке C:Program FilesPostgreSQL10

Все распаковал, все устанивилось, окно закрылось. Дальше сделал по инструкции — открыл командную строку, ввел

setx PATH «%PATH%;C:Program FilesPostgreSQL10bin»

В ответ комп пишет: «Предупреждение. Сохраненные данные будут усечены до 1024 знаков. Успех. Указанное значение сохранено.»

Далее, по инструкции закрыл командую строку, перезагрузился. И. Н-И-Ч-Е-Г-О, в командной строке при попытке ввести хотя бы psql выдается «psql» не является внутренней или внешней командой, исполняемой программой или пакетным файлом.

Ну что еще то надо? Руки опускаются от этих бесконечных инструкций, которые не работают! Помогите, гуру Джанги….

I have installed postgresql 10 on my windows 10 and added those paths

(C:Program FilesPostgreSQL10bin) , (C:Program
FilesPostgreSQL10lib)

but when i go to the CMD under administration rights and test PSQL or psql —version … i still get the same error

'psql' is not recognized as an internal or external command

i tried echo %path% and i can see the path there correct

I’m actually trying to link Flask to Heroku database that is why i have installed Postgresql so the pc can be familiar with psql commands

davidism's user avatar

davidism

117k25 gold badges382 silver badges332 bronze badges

asked Sep 11, 2018 at 18:03

X-x's user avatar

Have you added the Postgres binaries to your path in windows? It would seem that this is a likely cause of your issue.

To add to your path follow these steps (pulled from https://www.java.com/en/download/help/path.xml — yes I know it is java but the premise is the same):

  1. Windows 10 and Windows 8
  2. In Search, search for and then select: System (Control Panel)
  3. Click the Advanced system settings link.
  4. Click Environment Variables.
  5. In the section System Variables, find the PATH environment variable and select it. Click Edit.
  6. If the PATH environment variable does not exist, click New.
  7. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable.
  8. Click OK.
  9. Close all remaining windows by clicking OK.
  10. Reopen Command prompt window, and run your java code. (in our case psql)

You would add the bin folder to your path rather than just an individual binary.
For reference also see this question: How to set Postgres path variable on Windows 10

a_horse_with_no_name's user avatar

answered Sep 11, 2018 at 18:22

hgoscenski's user avatar

hgoscenskihgoscenski

3162 silver badges5 bronze badges

8

I was trying to fix this error as well, then I stumbled on this post I was able to fix this using choco install postgresql. This worked well for me.

answered Oct 21, 2022 at 19:22

Abanga Samuel's user avatar

After every installation of postgresql server you need to set bash profile to the respective postgres binaries, default postgres binaries resides at /usr/Version/bin for example /usr/pgsql-9.6/bin

cigien's user avatar

cigien

56.8k11 gold badges69 silver badges107 bronze badges

answered Feb 10, 2019 at 17:17

Naresh Gandi's user avatar

I have installed postgresql 10 on my windows 10 and added those paths

(C:Program FilesPostgreSQL10bin) , (C:Program
FilesPostgreSQL10lib)

but when i go to the CMD under administration rights and test PSQL or psql —version … i still get the same error

'psql' is not recognized as an internal or external command

i tried echo %path% and i can see the path there correct

I’m actually trying to link Flask to Heroku database that is why i have installed Postgresql so the pc can be familiar with psql commands

davidism's user avatar

davidism

117k25 gold badges382 silver badges332 bronze badges

asked Sep 11, 2018 at 18:03

X-x's user avatar

Have you added the Postgres binaries to your path in windows? It would seem that this is a likely cause of your issue.

To add to your path follow these steps (pulled from https://www.java.com/en/download/help/path.xml — yes I know it is java but the premise is the same):

  1. Windows 10 and Windows 8
  2. In Search, search for and then select: System (Control Panel)
  3. Click the Advanced system settings link.
  4. Click Environment Variables.
  5. In the section System Variables, find the PATH environment variable and select it. Click Edit.
  6. If the PATH environment variable does not exist, click New.
  7. In the Edit System Variable (or New System Variable) window, specify the value of the PATH environment variable.
  8. Click OK.
  9. Close all remaining windows by clicking OK.
  10. Reopen Command prompt window, and run your java code. (in our case psql)

You would add the bin folder to your path rather than just an individual binary.
For reference also see this question: How to set Postgres path variable on Windows 10

a_horse_with_no_name's user avatar

answered Sep 11, 2018 at 18:22

hgoscenski's user avatar

hgoscenskihgoscenski

3162 silver badges5 bronze badges

8

I was trying to fix this error as well, then I stumbled on this post I was able to fix this using choco install postgresql. This worked well for me.

answered Oct 21, 2022 at 19:22

Abanga Samuel's user avatar

After every installation of postgresql server you need to set bash profile to the respective postgres binaries, default postgres binaries resides at /usr/Version/bin for example /usr/pgsql-9.6/bin

cigien's user avatar

cigien

56.8k11 gold badges69 silver badges107 bronze badges

answered Feb 10, 2019 at 17:17

Naresh Gandi's user avatar

Содержание

  1. команда postgres «psql» не распознается в среде windows
  2. 4 ответов
  3. Setting Windows PATH for Postgres tools
  4. 26 Comments
  5. pg:psql might not work on windows? #334
  6. Comments
  7. will commented May 24, 2012
  8. geemus commented Jul 18, 2012
  9. stprior commented Aug 16, 2012
  10. geemus commented Aug 16, 2012
  11. Nawshine commented Oct 9, 2012
  12. arcseldon commented Oct 20, 2012
  13. arcseldon commented Oct 20, 2012
  14. slachterman commented Dec 3, 2012
  15. MrSwitch commented Dec 20, 2012
  16. gmusic commented Oct 27, 2013
  17. yloewidt commented Dec 2, 2013
  18. albertlyu commented May 17, 2014
  19. adamscruggs commented Jun 3, 2014
  20. adamscruggs commented Jun 3, 2014
  21. geemus commented Jul 14, 2014
  22. sethlivingston commented Jan 13, 2015
  23. mclain-c commented Feb 7, 2015
  24. MalikRumi commented Mar 16, 2015
  25. will commented Mar 16, 2015
  26. MalikRumi commented Mar 19, 2015
  27. psql command not found
  28. About the psql command
  29. What can I do with psql?
  30. How can I fix the psql command not found error on Linux?
  31. Summary
  32. Postgres «psql not recognized as an internal or external command»
  33. 11 Answers 11
  34. Important note:

команда postgres «psql» не распознается в среде windows

кажется, я его настроил, у меня есть моя база данных.yml с помощью postgres, и я могу подключить базу данных с pgadmin III, но когда я попытался с помощью команды psql проверить, какая версия, она говорит, что не распознается? Есть идеи, что мне делать?

Я использую windows и использую командную строку с Ruby on Rails. Использование PostgreSQL 9.2, установленного с помощью установщика EnterpriseDB one-click.

4 ответов

предполагая, что вы установили PostgreSQL в Windows с установщиком PostgreSQL «One-click», упакованным EnterpriseDB, psql не добавляется к PATH автоматически. Это отчасти потому, что добавление его в путь может вызвать путаницу, когда у людей установлено несколько версий PostgreSQL.

или добавить psql для переменные среды, см. например этот руководство.

Открыть Командную Строку

если на строке выше не отображается версия psql, выполните следующие действия

Откройте командную строку и повторите

если есть пробел после ****** ; тогда это не сработает. Вы действительно можете ввести %PATH% в командной строке cmd и посмотреть, как ваша переменная среды и пространство выглядит. Я пробовал оба случая для вас, первый с пространством имел ту же ошибку, о которой Вы упомянули, а второй без пространства работал.

вам нужно установить как bin, так и путь lib в переменной среды PATH, разделенной точкой с запятой:

%PROGRAMFILES\%с PostgreSQL 9.2 ОГРН;%PROGRAMFILES%\с PostgreSQL 9.2Либ

Источник

Setting Windows PATH for Postgres tools

If, after installing PostgreSQL, you face “psql not recognized as an internal or external command” error when you try to run psql from command prompt, then most probably all you need to do to solve this problem is to add the Postgres’s bin directory to the PATH system variable (the PATH is a system variable which allows Windows with the help of the Command prompt or the Terminal window find executables).

In this blog post, we’ll share seven simple steps that describe how to add the folder to the Windows 10 PATH variable.

Step 1. Run Windows Search on your Windows 10 machine by pressing WIN+S. You will see the Search Textbox.

Setting Windows PATH for Postgres tools Win S

Setting Windows PATH for Postgres tools environment

Setting Windows PATH for Postgres tools System Properties

Go to the “Advanced” tab and click on the “Environment Variables” button at the bottom. The “Performance,” “User Profiles,” and “Startup and Recovery” options can also be set in this tab.

Step 4. The “Environment Variables” window will be opened. This is divided into two boxes with User variables and System variables – where all variables and their values are displayed.

Setting Windows PATH for Postgres tools System variables Path

Find the “Path” variables in the System variables box, as shown in the screenshot above.

Step 5. Double click on the “Path” variable.

The list with all Path variables will be opened, where the Path variables can be edited, added, and deleted.

Setting Windows PATH for Postgres tools edit Path variables

Setting Windows PATH for Postgres tools new Path variables

Andrew
March 26, 2020 @ 4:31 pm

Thank you!! Exactly what I needed.

Mathew Dunbaugh
April 16, 2020 @ 12:55 am

Awesome. This is the most simple, straightforward answer I could find. Thanks.

Walter Mazvuru
April 22, 2020 @ 5:10 am

Thanks for the heads up! It is the best solution I have seen so far.

Muhammadhusayn Olimjonov
May 7, 2020 @ 3:34 pm

thank you very much! i have been stuck for a long time until I found this. thank you again!

Mercy Kipkoros
June 24, 2020 @ 3:07 am

Thanks a lot for this, I was stuck a whole day on it and you solved my problem in less than 20 min.

Naveen
July 1, 2020 @ 7:32 am

Thanks You 🙂
Very Helpful and Informative 🙂

Lebene
July 3, 2020 @ 2:16 pm

I cannot however just enter psql and go. It is showing my normal C drive user acc as the default e.g. C:UsersMe> and then if I type psql, it asks for my user password which does not work.

What can I do? On postgres 12. Thank you

Jay
July 6, 2020 @ 6:06 pm

Emilia
June 3, 2022 @ 8:00 pm

path
July 19, 2020 @ 9:39 pm

Is this the default system variable in Windows 10? Because I accidentally deleted the value of path, and PATHEXT, and restarted the computer, the computer restore did not open. Now the command window CMD input other commands are not internal or internal commands. What should I do?

Anonymous
August 20, 2020 @ 7:02 pm

Anonymous
October 20, 2020 @ 9:15 am

Daniel McLaren
December 1, 2020 @ 6:58 am

Brilliant, the screenshots really helped. Thanks

Ezrqn Kemboi
January 16, 2022 @ 2:13 am

This works very well.

Esther
February 12, 2022 @ 9:22 pm

Thank you so much, exactly what I need

Anonymous
March 20, 2022 @ 9:52 am

Cornelia
March 30, 2022 @ 12:10 pm

Thanks, first of all! All done, I can see the path on my command line when echo %PATH%, but still if I try to type any command using psql the output is the same : ‘psql’ is not recognized as an internal or external command,
operable program or batch file…..what can I do to solve the issue? Thanks

Alex
April 1, 2022 @ 10:06 am

This issue can happen if:
1. There is no psql.exe utility in the directory that is in the PATH variable
2. The computer hasn’t been restarted after changing the variable

Anonymous
April 5, 2022 @ 1:02 pm

Thank you very much

Jaloliddin Murodullayev
June 22, 2022 @ 10:11 am

Binoj Joseph
June 23, 2022 @ 7:44 pm

Bilbo Bct
July 2, 2022 @ 8:38 am

That was quite helpful. Thanks!!

Cristhian
July 21, 2022 @ 11:02 pm

Nice, it’s working for me

Anonymous
July 24, 2022 @ 12:20 am

Really clearly explained and helpful, thanks.

Anonymous
August 19, 2022 @ 5:20 am

Lyle R.
September 16, 2022 @ 12:03 pm

I’ve had a problem with pythons pg_config not being on a path. I’ve never worked with this PATH and my whole backend development team of mine has been waiting more than a week to get things fixed for ready for production. I’ve looked everywhere for how to do this and this is one of the only hands-down straight-up examples there for this.

Источник

pg:psql might not work on windows? #334

from someone writing into to devcenter feedback

After installing postgresql on windows, I’m unable to run heroku pg:psql. It gives me the message «The local psql command could not be located». I tried adding the path to the PATH environment variable. I’m able to run the command myself (by typing psql), but heroku still can’t find the executable.

The text was updated successfully, but these errors were encountered:

I haven’t heard any further info here (and don’t really have direct access to ask them follow up questions). So I’ll close for now, but keep an eye out.

When this occurred for me the issue was with quotes in the Windows path, so just a local config issue.

Originally I had «C:Program FilesPostgreSQL9.1bin» (with quotes) at the end of PATH. The PSQL command runs, but starts by displaying:
could not find a «psql» to execute

Running «heroku pg:psql DBNAME» failed with the message «The local psql command could not be located».

After resetting PATH to leave out the quote PSQL runs without an error, and heroku pg:psql DBNAME connects to the remote DB.

Hello, I am getting a similar issue, I tried to remove the quotes in the path mentioned by stprior but it didnot solve the issue. Is there any other solution or things I need to check?
Thanks

Thank you stprior, your suggestion worked.

Make sure to restart the command shell after changing the contents of the Windows path. This solved my issue (after adding the Postgresql bin directory to my path).

In Command Prompt write:

set PATH=%PATH%;C:Program FilesPostgreSQL9.2bin

Change the above directory e.g. «C:Program FilesPostgreSQL9.2» to your installed postgresql’s ‘bin’ directory.

Anyone know how to get this working in the Cygwin bash terminal?

Mine still doesn’t work. but it worked on a friend’s computer

Same problem, Windows 8. Added C:Program FilesPostgreSQL9.3bin, didn’t work.
Added «C:Program FilesPostgreSQL9.3bin» Still didn’t work.

! The local psql command could not be located

When I run «heroku pg:psql»

I guess it’s not relevant When I run psql in the Command Line it runs and prompt for a password I don’t know(How can i retrieve it?)..

@yloewidt, were you ever able to solve this issue? I’m running Windows 7 and all my path variables are set up correctly, since I can access psql locally as well as run ‘heroku pg:psql’. pg:ps or pg:push, no luck.

I am also having this problem using Windows 8 and PG 9.3.4. Running psql at command prompt gives me the expected postgres=# prompt. However, running:

Returns «The local psql command could not be located». My PATH seems appropriately set up, and when I run rails console and execute this statement:

I am presented with the postgres prompt. I’m looking through the code to see if I can figure out what is going on because it’s a frustrating problem to have.

What is happening is that dump_restore_cmd in pg_dump_restore.rb returns a string like this:

which is the string that’s called as part of the private run function here

Executing this on Windows raises Errno::ENOENT (because the Windows command line fails to find an executable called «env»), resulting in the error message we’re seeing. I think stripping out or changing the way the environment variables are set will fix this issue. For now, I’m just going to use this to format the statement the way I need it and run pg_dump and pg_restore manually.

@adamscruggs good catch and explanation. I’ve patched it on master here: 6f43cf7

I’ll try to get a release out soon. Part of the confusion above was that the error message looks the same, but has a much different cause (lacking psql in path vs lacking env in path). So hopefully we’ll have this sorted more completely soon.

Remove the quotes fixed my problem.

A reboot fixed it for me. I think because that forces cygwin to update its path.

@will I am on Windows 8.1 with Postgres 9.4 on AMD64. I have Postgres in my PATH, so I no longer get ‘the local psql could not be located’. However, it still does not work for me. Here is my output:

I just read your post on SO http://stackoverflow.com/questions/25870388/heroku-pgpull-failing-to-populate-schema. Surely there are other people on Windows who have successfully uploaded a database to Heroku. How are they doing it? Clearly I can’t stay on Heroku if I can’t use my database.

I just read your post on SO http://stackoverflow.com/questions/25870388/heroku-pgpull-failing-to-populate-schema. Surely there are other people on Windows who have successfully uploaded a database to Heroku. How are they doing it? Clearly I can’t stay on Heroku if I can’t use my database.

Yes, you can upload a database, you just can’t use the heroku command to do it.

you need to look at the full url with heroku config of the database and first use pg_dump to take a dump of your local database, and then PG_PASSWORD=

if you want to restore a local dump to heroku

I could not get Git Bash to accept these commands. It kept saying «pg_dump:
too many command-line arguments (first is «-f»)» Is this a Windows issue?

But uploading to Dropbox and then restoring from there worked, so it is
there without all the flags. Now I have an import error so until that is
resolved I don’t really know what I have for a db. Thx.

On Mon, Mar 16, 2015 at 2:07 PM, Will Leinweber notifications@github.com
wrote:

I just read your post on SO
http://stackoverflow.com/questions/25870388/heroku-pgpull-failing-to-populate-schema.
Surely there are other people on Windows who have successfully uploaded a
database to Heroku. How are they doing it? Clearly I can’t stay on Heroku
if I can’t use my database.
Yes, you can upload a database, you just can’t use the heroku command to
do it.


Reply to this email directly or view it on GitHub
#334 (comment).

Источник

psql command not found

PostgreSQL is a very popular database engine used by a lot of websites, is one of the most used relational database management system available, and after installing it we can use some tools that it includes. One of these tools is a command-line tool called psql, and today we are going to learn a lot about it, and how to fix the famous ‘psql command not found’ error on your systems.

About the psql command

So as we said, the psql command is related to the PostgreSQL RDBMS. But what does this command do exactly? Let’s start by explaining that.

psql is a command-line tool that grants us the ability to interact with the PostgreSQL RDBMS using the command line o terminal of our system.

There are different ways to use or interact with an RDBMS. Some of these are graphic programs like phpMyAdmin, which is used for another RDBMS called MySQL (there is a version of it for PostgreSQL too), and there are less graphic ways like the command-line or terminal. But why would someone use a terminal if a nice software with a nice GUI can be used instead?

Well, some people are more used to the terminal, and in some cases the features available in these tools are different, so even if you do have a GUI to interact with an RDBMS you may be lacking a function that is available in the terminal, and vice versa of course.

What can I do with psql?

As we said, it is used to connect with PostgreSQL so we can then issue different queries, and of course, see the results of those queries. It includes a lot of functions, around 30 to be more precise, but some are more important than others so let’s see which of these functions or options are used the most.

How can I fix the psql command not found error on Linux?

So now that we have explained what psql is exactly and how it can be used to interact with PostgreSQL databases let’s see how can we resolve one of the most common problems associated with this tool: the not found error.

If you ever come across the psql command not found error then you may, or may not, be doing something wrong. Before explaining the solution, let’s see what is going on here.

When you get the psql not found error it means that the binary/executable file for psql wasn’t found in your user’s PATH. Depending on how PostgreSQL was installed it may or may not be placed in your PATH.

We can also get this error if we haven’t installed PostgreSQL yet, in which case the solution is to install it of course and check again after that.

But what if PostgreSQL is installed but you still get this error anyway? Well, don’t worry, it’s pretty easy to solve this problem, and this solution works for both CentOS and Ubuntu systems, and for most Linux distros actually.

First, let’s run a very useful command called ‘updatedb’, which nowadays comes included in most distros by default as a part of the ‘locate’ tool. It may run for a few minutes before finishing:

Once it finishes, the locate cache database will be updated and we can use it to find the exact location of the psql command, so let’s run this in our shell:

Once the exact path of the binary is found we only have to create a symlink. For example, if the psql binary was found in the path ‘/usr/lib/postgresql/9.5/bin/psql’ then we only need to issue the following command to create a symlink:

This way the binary will be available in our PATH and we will be able to execute it quickly just by typing “psql” in our shell. This is the easiest and quickest way to solve the psql command not found error.

Summary

So today we have learned a bit more about the psql tool which is used in the shell to issue commands and queries in PostgreSQL, and it can also be used in bash scripts that connect to this RDBMS.

We also know how to fix the psql command not found error, which is one of the most common errors related to this tool. The solution is quite easy and is compatible with most Linux distros, requiring only a symlink to add the binary to the user’s PATH.

Источник

Postgres «psql not recognized as an internal or external command»

For Postgres, I keep getting this error multiple times even though I have already set the location of the bin folder to the path variable in Windows 8. Is there something else I’m missing?

(I can’t post pictures since I don’t have enough reputation)

11 Answers 11

Just an update because I was trying it on Windows 10 you do need to set the path to the following: ;C:Program FilesPostgreSQL9.5bin ;C:Program FilesPostgreSQL9.5lib

You can do that either through the CMD by using set PATH [the path] or from my

computer => properties => advanced system settings=> Environment Variables => System Variables

Then search for path.

Important: don’t replace the PATHs that are already there just add one beside them as follows ;C:Program FilesPostgreSQL9.5bin ;C:Program FilesPostgreSQL9.5lib

Please note: On windows 10, if you follow this: computer => properties => advanced system settings=> Environment Variables => System Variables> select PATH, you actually get the option to add new row. Click Edit, add the /bin and /lib folder locations and save changes.

Important note:

Replace 9.5 with your current version number. As of 2022, that is 13

It could be that your server doesn’t start automatically on windows 10 and you need to start it yourself after setting your Postgresql path using the following command in cmd:

You need to be inside «C:Program FilesPostgreSQL11.4bin» directory to execute the above command.

FFjQl

You still need to be inside the bin directory to work with psql

2cRdb

I had your issue and got it working again (on windows 7).

I deleted the PATH variables above one at a time to test if they were both really needed. Psql continued to work after I deleted the lib path, but stopped working after I deleted the bin path. When I returned bin, it still didn’t work, and the same with lib. I closed and reopened the command line between tries, and checked the path. The problem lingered even though the path was identical to how it had been when working. I re-pasted it.

I uninstalled and reinstalled postgres. The problem lingered. It finally worked after I deleted the spaces between the «; C. » in the paths and re-saved.

Not sure if it was really the spaces that were the culprit. Maybe the environment variables just needed to be altered and refreshed after the install.

I’m also still not sure if both lib and bin paths are needed since there seems to be some kind of lingering memory for old path configurations. I don’t want to test it again though.

Источник

Что касается Postgres, я продолжаю получать эту ошибку несколько раз, хотя я уже установил местоположение папки bin в переменной пути в Windows 8. Что-то еще мне не хватает?

(Я не могу публиковать фотографии, так как у меня недостаточно репутации)

10 ответов

Лучший ответ

Просто обновление, потому что я пробовал его в Windows 10, вам нужно указать следующий путь: ;C:Program FilesPostgreSQL9.5bin ;C:Program FilesPostgreSQL9.5lib

Вы можете сделать это либо через CMD, используя set PATH [the path] или из моего

компьютер => свойства => расширенные настройки системы => переменные среды => системные переменные

Затем ищите путь.

Важно: не заменяйте уже имеющиеся ПУТЬ, просто добавьте один рядом с ними следующим образом ;C:Program FilesPostgreSQL9.5bin ;C:Program FilesPostgreSQL9.5lib

Обратите внимание : в Windows 10, если вы выполните следующее: компьютер => свойства => дополнительные системные настройки => переменные среды => системные переменные> выберите ПУТЬ, вы фактически получите возможность добавить новую строку. Нажмите Edit, добавьте расположение папок / bin и / lib и сохраните изменения.

Затем закройте командную строку, если она открыта, а затем запустите ее снова. попробуйте psql —version Если он дает вам ответ, то все в порядке, если нет, попробуйте echo %PATH% и посмотрите, был ли добавлен заданный вами путь или нет, и правильно ли он добавлен.


103

Hossain Mahmood Tuhin
11 Окт 2018 в 07:59

Всегда лучше установить предыдущую версию или при установке убедитесь, что вы указали ‘/ data’ в отдельной папке каталога «C: data»


0

Tshiamo Motshabi
6 Окт 2020 в 14:14

Простое решение, которое не упоминалось в этом вопросе: перезагрузите компьютер после объявления переменной пути.

Мне всегда приходится перезагружать — путь никогда не обновляется, пока я не сделаю это. И когда я перезапускаю, путь всегда обновляется.


0

Michael Jay
18 Апр 2020 в 19:23

Найдите свой двоичный файл, в котором он сохранен. получить путь в конечной шахте

C:UsersLENOVODocumentspostgresql-9.5.21-1-windows-x64-binaries (1)pgsqlbin

Затем найдите свой локальный путь к данным пользователя, он в основном

C:usrlocalpgsqldata

Теперь все, что нам нужно, это ввести следующую команду в пути двоичного терминала:

C:UsersLENOVODocumentspostgresql-9.5.21-1-windows-x64-binaries (1)pgsqlbin>pg_ctl -D "C:usrlocalpgsqldata" start

Сделано!


1

Anupam Maurya
13 Май 2020 в 23:10

Введите этот путь в системную переменную среды .

C:Program FilesPostgreSQL[YOUR PG VERSION]bin

В этом случае я использую версию 10. Если вы проверите папку postgres, вы увидите свои текущие версии.

В моем случае я использовал следующие строки в отдельных строках:

C:Program FilesPostgreSQL10bin
C:Program FilesPostgreSQL10lib


2

Divine Hycenth
16 Янв 2020 в 13:34

Даже если уже немного поздно, я решил проблему PATH, удалив все пробелы.

;C:Program FilesPostgreSQL9.5bin;C:Program FilesPostgreSQL9.5lib

У меня работает сейчас.


2

CertainPerformance
17 Авг 2018 в 08:41

Убедитесь, что путь действительно ведет к исполняемым файлам. Я использую версию 11, и она не работала, пока она не была указана в качестве пути:

C:Program FilesPostgreSQL11binbin

Возможно, так устроена версия 11, или я как-то испортил установку, но с тех пор у меня не было проблем.


5

Nate
13 Фев 2019 в 04:38

Если вы попробовали все ответы, но голова все еще кружится, не забудьте сменить версию на ту, которую вы скачали.

Например, не копируйте просто

;C:Program FilesPostgreSQL9.5bin ;C:Program FilesPostgreSQL9.5lib

Более ясно,

;C:Program FilesPostgreSQL[Your Version]bin ;C:Program FilesPostgreSQL[Your Version]lib

Я кружил головой. Надеюсь это поможет.


5

creamCheeseCoder
13 Дек 2018 в 04:49

У меня была ваша проблема, и она снова заработала (в Windows 7).

Моя установка сначала действительно работала. Я установил postgres, а затем настроил системные переменные PATH с помощью {{X0 }}. Ключевое слово psql в командной строке не дало ошибок.

Я удалил указанные выше переменные PATH по одной, чтобы проверить, действительно ли они нужны. Psql продолжал работать после того, как я удалил путь к lib, но перестал работать после того, как я удалил путь к bin. Когда я вернул bin, он все еще не работал, то же самое и с lib. Я закрыл и снова открыл командную строку между попытками и проверил путь. Проблема сохранялась, хотя путь был идентичен тому, каким он был при работе. Я его перепрошил.

Я удалил и переустановил postgres. Проблема не исчезла. Это, наконец, сработало после того, как я удалил пробелы между «; C: …» в путях и повторно сохранил.

Не уверен, действительно ли виноваты были пробелы. Возможно, переменные среды просто нужно было изменить и обновить после установки.

Я также все еще не уверен, нужны ли пути как lib, так и bin, поскольку, похоже, для старых конфигураций пути существует какая-то устаревшая память. Однако я не хочу проверять это снова.


5

voluntier
27 Ноя 2016 в 09:18

Windows 10

Возможно, ваш сервер не запускается автоматически в Windows 10, и вам нужно запустить его самостоятельно после установки пути Postgresql, используя следующую команду в cmd:

pg_ctl -D "C:Program FilesPostgreSQL11.4data" start

Вы должны находиться в каталоге «C: Program Files PostgreSQL 11.4 bin», чтобы выполнить указанную выше команду.

EX :

enter image description here

Для работы с psql вам все еще нужно находиться в каталоге bin


7

Abdel-Raouf
18 Июл 2019 в 18:17

Кажется, я его настроил, у меня есть база данных.yml с помощью postgres, и я могу подключить базу данных с помощью pgadmin III, но когда я попытался использовать команду psql для проверки, какая версия, он говорит, что не распознан? Любая идея, что я должен делать?

Я использую окна и использую командную строку с Ruby on Rails. Использование PostgreSQL 9.2, установленного с помощью установщика EnterpriseDB одним щелчком мыши.

4 ответы

Предполагая, что вы установили PostgreSQL в Windows с помощью установщика PostgreSQL «в один клик», упакованного EnterpriseDB, psql не добавляется в PATH автоматически. Отчасти это связано с тем, что в противном случае добавление его к пути может вызвать путаницу, если у людей установлено несколько версий PostgreSQL.

Вам нужно указать полный явный путь к psql, например:

"%PROGRAMFILES%Postgresql9.2binpsql.exe"

или добавить psql пользователю PATH переменная среды, см., например это руководство.

ответ дан 08 апр.

Открыть командную строку

psql --version

если в приведенной выше строке версия psql не отображается, выполните следующие действия.

(For Windows 7 OS)

Mycomputer->Properties->Advanced System Settings->EnvironmentVariables->Path->Edit->
(Donot remove any existing Path)

Добавь это

;C:Program FilesPostgreSQL9.5bin;C:Program FilesPostgreSQL9.5lib

сохранить его тогда

Снова откройте командную строку и повторите

psql --version

C:Usersrumi>psql --version

psql (PostgreSQL) 9.5.0

Создан 27 янв.

это потому, что не должно быть места между ; и ваш путь к psql, поэтому он должен быть таким *****;C:Program FilesPostgreSQL9.2bin.

Если есть пробел после ******; тогда это не сработает. Вы действительно можете ввести %PATH%в командной строке cmd и посмотрите, как выглядит ваша переменная среды и пространство. Я пробовал оба случая для вас, первый с пробелом имел ту же ошибку, которую вы упомянули, а второй без пробела работал.

ответ дан 12 авг.

Вам нужно установить как путь к bin, так и путь к lib в вашей переменной среды PATH, разделенной точкой с запятой:

%PROGRAMFILES%Postgresql9.2bin;%PROGRAMFILES%Postgresql9.2lib

ответ дан 14 окт ’14, 21:10

Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками

ruby-on-rails
database
postgresql

or задайте свой вопрос.

Похоже, что я настроил его, у меня есть database.yml с помощью postgres, и я могу подключить базу данных с помощью pgadmin III, но когда я попытался использовать команду psql для проверки какой версии, он говорит, что это не признал? Любая идея, что я должен делать?

Я использую окна и используя командную строку с Ruby on Rails. Использование PostgreSQL 9.2, установленного с установщиком EnterpriseDB с одним щелчком мыши.

4b9b3361

Ответ 1

Предполагая, что вы установили PostgreSQL в Windows с установщиком PostgreSQL «Один клик», упакованным EnterpriseDB, psql автоматически не добавляется в PATH. Это отчасти потому, что добавление этого пути в путь может вызвать путаницу, когда у людей есть несколько версий PostgreSQL.

Вам нужно указать полный явный путь к psql, например:

"%PROGRAMFILES%Postgresql9.2binpsql.exe"

или добавить psql к переменной среды PATH пользователя, см., например, это руководство.

Ответ 2

Открыть командную строку

psql --version

если на приведенной выше строке версия psql не отображается, выполните следующие шаги

(For Windows 7 OS)

Mycomputer->Properties->Advanced System Settings->EnvironmentVariables->Path->Edit->
(Donot remove any existing Path)

Добавьте это

;C:Program FilesPostgreSQL9.5bin;C:Program FilesPostgreSQL9.5lib

сохраните его, затем

Повторно открыть командную строку и повторить

psql --version

C:Usersrumi>psql --version

psql (PostgreSQL) 9.5.0

Ответ 3

это потому, что между ; и вашим psql-контуром не должно быть пробела, поэтому оно должно быть как *****;C:Program FilesPostgreSQL9.2bin.

Если после ****** есть пробел; то это не сработает. Вы можете набрать %PATH% в командной строке cmd и посмотреть, как выглядит ваша переменная среды и пространство. Я попробовал оба случая для вас, первый с пространством имел ту же ошибку, о которой вы говорили, а вторая без пробела.

Ответ 4

Вам необходимо установить путь bin и lib в переменной среды PATH, разделенной точкой с запятой:

% ProgramFiles%Postgresql9,2Bin,% ProgramFiles%Postgresql9,2Lib

Понравилась статья? Поделить с друзьями:
  • Кодировщик mpeg 2 для dvd студия windows
  • Команда ping в командной строке windows
  • Команда php не работает в консоли windows
  • Кодировке utf 8 или windows 1251
  • Команда net send в windows 10