I have installed Postgresql on my Windows 10 PC. I have used the pgAdmin II tool to create a database called company, and now I want to start the database server running. I cannot figure out how to do this.
I have run the start command on the postgres command line, and nothing seems to happen.
What I doing is:
postgres=# pg_ctl start
postgres=# pg_ctl status
postgres=# pg_ctl restart
postgres=# pg_ctl start company
postgres=# pg_ctl status
…..-> I am seeing nothing returned.
mikemaccana
112k99 gold badges392 silver badges497 bronze badges
asked Apr 14, 2016 at 17:25
3
Go inside bin folder in C drive where Postgres is installed.
run following command in git bash or Command prompt:
pg_ctl.exe restart -D "<path upto data>"
Ex:
pg_ctl.exe restart -D "C:\Program Files\PostgreSQL\9.6\data"
Another way:
type «services.msc» in run popup(windows + R).
This will show all services running
Select Postgres service from list and click on start/stop/restart.
Thanks
answered Oct 5, 2017 at 9:42
0
If you have installed postgres via the Windows installer you can start it in Services like so:
answered Oct 30, 2018 at 10:28
Matthew LockMatthew Lock
13.2k12 gold badges92 silver badges130 bronze badges
6
pg_ctl
is a command line (Windows) program not a SQL statement. You need to do that from a cmd.exe
. Or use net start postgresql-9.5
If you have installed Postgres through the installer, you should start the Windows service instead of running pg_ctl
manually, e.g. using:
net start postgresql-9.5
Note that the name of the service might be different in your installation. Another option is to start the service through the Windows control panel
I have used the pgAdmin II tool to create a database called company
Which means that Postgres is already running, so I don’t understand why you think you need to do that again. Especially because the installer typically sets the service to start automatically when Windows is started.
The reason you are not seeing any result is that psql
requires every SQL command to be terminated with ;
in your case it’s simply waiting for you to finish the statement.
See here for more details: In psql, why do some commands have no effect?
answered Apr 14, 2016 at 18:27
4
After a lot of searching and testing, I’ve found a solution.
If you are in Windows
-
Find the
PG Databases
directory and execute the following command as asql command
in pgAdmin query tools$ show data_directory;
result :
------------------------ - D:/PG_DATA/data - ------------------------
-
Go to the
bin
directory of your postgres installation (in my case it’s located in «c:/programms/postgresSql/bin») -
Open a command prompt (CMD) and execute the following command:
pg_ctl -D "D:\PSG_SQL\data" restart
That should do it.
answered Dec 7, 2016 at 16:41
HichamEchHichamEch
6451 gold badge10 silver badges20 bronze badges
2
The simplest way to start/stop/restart the installed PostgreSQL Server on your Windows device is as follows:
- Start ->
net start postgresql-x64-14
- Stop ->
net stop postgresql-x64-14
- Restart ->
net stop postgresql-x64-14 && net start postgresql-x64-14
The version number must be changed to take into account the installed version of your PostgreSQL Server.
answered Dec 1, 2021 at 20:35
For windows the following command worked well for me
pg_ctl.exe restart -D «<path_to_data>»
Eg: pg_ctl.exe restart -D «D:\Program Files\PostgreSQL\13\data»
answered Jul 1, 2021 at 17:05
There are different way to open PostgreSql database .
1> One of them is by going windows and select pgAdmin4 or pgAdmin3 depends to version you use and entering password you can access you database .
2> Another one is by terminal :
To able to select from terminal you have to add the path of your installed postgresql by going enviroment variables . To do that got to installed postgresql file and select the path of bin and add to enviroment variable of window setting .
after that you can type in terminal : psql -U postgres -h localhost
Hit enter and it ask you password . After giving password you can create database and tables and can access it .
answered Apr 18, 2021 at 15:35
Jeevan RupachaJeevan Rupacha
3,3351 gold badge16 silver badges29 bronze badges
If you are getting an error «psql.exe’ is not recognized as an internal or external command,… «
There can be :
Causes
- System is unable to find the psql.exe tool, because the path to this tool is not specified in the system environment variable PATH
or
— PostgreSQL Database client not installed on your PC
Since you have already installed PostgreSQL the latter can not be the issue(assuming everything is installed as expected)
In order to fix the first one «please specify the full path to the bin directory in the PostgreSQL installation folder, where this tool resides.»
For example
Path: «C:\Program Files\PostgreSQL\10\bin»
answered May 10, 2018 at 7:53
I found using
net start postgres_service_name
the only reliable way to operate Postgres on Windows
answered May 17, 2018 at 8:23
first find your binaries file where it is saved.
get the path in terminal mine is
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries
(1)\pgsql\bin
then find your local user data path, it is in mostly
C:\usr\local\pgsql\data
now all we have to hit following command in the binary terminal path:
C:\Users\LENOVO\Documents\postgresql-9.5.21-1-windows-x64-binaries (1)\pgsql\bin>pg_ctl -D "C:\usr\local\pgsql\data" start
all done!
autovaccum launcher started! cheers!
answered May 13, 2020 at 23:08
Remove Postmaster file in «C:\Program Files\PostgreSQL\9.6\data»
and restart the PostgreSQL services
answered Aug 17, 2019 at 13:10
I was try to solve the problem with Windows Terminal and I’ve cannot to solve it. Use Windows R + cmd (if you are using Windows) for it work!
answered Oct 8, 2021 at 18:39
The easiest way to enable pg_ctl command is to go to your PostgreSQL directory ~\PostgreSQL\version\bin\
and execute the pg_ctl.exe
. Afterwards the pg_ctl commands will be available.
answered Jan 5, 2021 at 2:11
PostgreSQL — это бесплатная объектно-реляционная СУБД с мощным функционалом, который позволяет конкурировать с платными базами данных, такими как Microsoft SQL, Oracle. PostgreSQL поддерживает пользовательские данные, функции, операции, домены и индексы. В данной статье мы рассмотрим установку и краткий обзор по управлению базой данных PostgreSQL. Мы установим СУБД PostgreSQL в Windows 10, создадим новую базу, добавим в неё таблицы и настроим доступа для пользователей. Также мы рассмотрим основы управления PostgreSQL с помощью SQL shell и визуальной системы управления PgAdmin. Надеюсь эта статья станет хорошей отправной точкой для обучения работы с PostgreSQL и использованию ее в разработке и тестовых проектах.
Содержание:
- Установка PostgreSQL 11 в Windows 10
- Доступ к PostgreSQL по сети, правила файерволла
- Утилиты управления PostgreSQL через командную строку
- PgAdmin: Визуальный редактор для PostgresSQL
- Query Tool: использование SQL запросов в PostgreSQL
Установка PostgreSQL 11 в Windows 10
Для установки PostgreSQL перейдите на сайт https://www.postgresql.org и скачайте последнюю версию дистрибутива для Windows, на сегодняшний день это версия PostgreSQL 11 (в 11 версии PostgreSQL поддерживаются только 64-х битные редакции Windows). После загрузки запустите инсталлятор.
В процессе установки установите галочки на пунктах:
- PostgreSQL Server – сам сервер СУБД
- PgAdmin 4 – визуальный редактор SQL
- Stack Builder – дополнительные инструменты для разработки (возможно вам они понадобятся в будущем)
- Command Line Tools – инструменты командной строки
Установите пароль для пользователя postgres (он создается по умолчанию и имеет права суперпользователя).
По умолчание СУБД слушает на порту 5432, который нужно будет добавить в исключения в правилах фаерволла.
Нажимаете Далее, Далее, на этом установка PostgreSQL завершена.
Доступ к PostgreSQL по сети, правила файерволла
Чтобы разрешить сетевой доступ к вашему экземпляру PostgreSQL с других компьютеров, вам нужно создать правила в файерволе. Вы можете создать правило через командную строку или PowerShell.
Запустите командную строку от имени администратора. Введите команду:
netsh advfirewall firewall add rule name="Postgre Port" dir=in action=allow protocol=TCP localport=5432
- Где rule name – имя правила
- Localport – разрешенный порт
Либо вы можете создать правило, разрешающее TCP/IP доступ к экземпляру PostgreSQL на порту 5432 с помощью PowerShell:
New-NetFirewallRule -Name 'POSTGRESQL-In-TCP' -DisplayName 'PostgreSQL (TCP-In)' -Direction Inbound -Enabled True -Protocol TCP -LocalPort 5432
После применения команды в брандмауэре Windows появится новое разрешающее правило для порта Postgres.
Совет. Для изменения порта в установленной PostgreSQL отредактируйте файл postgresql.conf по пути C:\Program Files\PostgreSQL\11\data.
Измените значение в пункте
port = 5432
. Перезапустите службу сервера postgresql-x64-11 после изменений. Можно перезапустить службу с помощью PowerShell:
Restart-Service -Name postgresql-x64-11
Более подробно о настройке параметров в конфигурационном файле postgresql.conf с помощью тюнеров смотрите в статье.
Утилиты управления PostgreSQL через командную строку
Рассмотрим управление и основные операции, которые можно выполнять с PostgreSQL через командную строку с помощью нескольких утилит. Основные инструменты управления PostgreSQL находятся в папке bin, потому все команды будем выполнять из данного каталога.
- Запустите командную строку.
Совет. Перед запуском СУБД, смените кодировку для нормального отображения в русской Windows 10. В командной строке выполните:
chcp 1251
- Перейдите в каталог bin выполнив команду:
CD C:\Program Files\PostgreSQL\11\bin
Основные команды PostgreSQL:
PgAdmin: Визуальный редактор для PostgresSQL
Редактор PgAdmin служит для упрощения управления базой данных PostgresSQL в понятном визуальном режиме.
По умолчанию все созданные базы хранятся в каталоге base по пути C:\Program Files\PostgreSQL\11\data\base.
Для каждой БД существует подкаталог внутри PGDATA/base, названный по OID базы данных в pg_database. Этот подкаталог по умолчанию является местом хранения файлов базы данных; в частности, там хранятся её системные каталоги. Каждая таблица и индекс хранятся в отдельном файле.
Для резервного копирования и восстановления лучше использовать инструмент Backup в панели инструментов Tools. Для автоматизации бэкапа PostgreSQL из командной строки используйте утилиту pg_dump.exe.
Query Tool: использование SQL запросов в PostgreSQL
Для написания SQL запросов в удобном графическом редакторе используется встроенный в pgAdmin инструмент Query Tool. Например, вы хотите создать новую таблицу в базе данных через инструмент Query Tool.
- Выберите базу данных, в панели Tools откройте Query Tool
- Создадим таблицу сотрудников:
CREATE TABLE employee
(
Id SERIAL PRIMARY KEY,
FirstName CHARACTER VARYING(30),
LastName CHARACTER VARYING(30),
Email CHARACTER VARYING(30),
Age INTEGER
);
Id — номер сотрудника, которому присвоен ключ SERIAL. Данная строка будет хранить числовое значение 1, 2, 3 и т.д., которое для каждой новой строки будет автоматически увеличиваться на единицу. В следующих строках записаны имя, фамилия сотрудника и его электронный адрес, которые имеют тип CHARACTER VARYING(30), то есть представляют строку длиной не более 30 символов. В строке — Age записан возраст, имеет тип INTEGER, т.к. хранит числа.
После того, как написали код SQL запроса в Query Tool, нажмите клавишу F5 и в базе будет создана новая таблица employee.
Для заполнения полей в свойствах таблицы выберите таблицу employee в разделе Schemas -> Tables. Откройте меню Object инструмент View/Edit Data.
Здесь вы можете заполнить данные в таблице.
После заполнения данных выполним инструментом Query простой запрос на выборку:
select Age from employee;
- Basic
PG_CTL
Initialization Commands in Windows - Use
SERVICES.MSC
toSTART/STOP
a PostgreSQL Session in Windows
Today, we will be learning how to start a PostgreSQL server on Windows. In the previous article about downloading and installing PostgreSQL on Windows, we already learned how to start a session, create a USER
, issue queries, and work with different database objects.
Our topic now focuses on trying to run a PostgreSQL server session to which other users in a local system can connect.
Basic PG_CTL
Initialization Commands in Windows
PG_CTL
is a utility used to start and control a PostgreSQL server. PG_CTL
is a manual setup for initializing a PostgreSQL session as it provides a controlled exit, encapsulates different tasks, and can be used for various operations related to our database.
To start a server on Windows, go to your command prompt inside the PostgreSQL installation for the BIN
folder.
pg_ctl start -D "[\data folder directory]";
This will start your PostgreSQL server. To do this on a different port on your computer on which you want other users to listen, use a query as follows.
pg_ctl -o "-F -p [post_number]" start
Enter your PORT NUMBER
in the port_number
defined without the brackets. This will help start your server and allow other users to connect to it on different systems.
However, if your PostgreSQL server stopped due to a reason or a slight malfunction, you are better off using any of the following commands to make it work.
pg_ctl restart -D "[\data folder];
pg_ctl start company; --may or may not work / may produce errors
...
Many times, there will be no need to do any of this. Starting PGADMIN
, for example, tends to already create a PostgreSQL session on a pre-defined port in your PC
, allowing other users to discover it easily.
There may be no need to write any of the commands given above to make your PostgreSQL server boot up.
Specify Paths While Issuing PG_CTL START/RESTART
in Windows
Sometimes, calling a simple PG_CTL START/RESTART
isn’t the way to go. You may need to specify the DATA
folder path within your PostgreSQL installation and then issue the boot commands.
Calling the queries given above, you will get an OUTPUT
.
Output:
pg_ctl: another server might be running; trying to start server anyway
waiting for server to start....2022-04-28 19:28:38.766 PKT [3228] LOG: redirecting log output to logging collector process
2022-04-28 19:28:38.766 PKT [3228] HINT: Future log output will appear in directory "log".
stopped waiting
pg_ctl: could not start server
Examine the log output.
The output given above happens when a PostgreSQL server is already running. Because we already had PGADMIN
booted up and running in the background, calling the query above would be unable to initialize a server on the port already being used.
However, doing something below would run separate servers on the same PC.
pg_ctl -o "-F -p 5656" start -D "C:\Program Files\PostgreSQL\14\data"
Output:
waiting for server to start....2022-04-28 19:34:04.588 PKT [11784] LOG: redirecting log output to logging collector process
2022-04-28 19:34:04.588 PKT [11784] HINT: Future log output will appear in directory "log".
done
server started
Similarly, you could also issue the same commands for RESTART
.
pg_ctl restart -D "C:\Program Files\PostgreSQL\14\data"
or
pg_ctl -o "-F -p 5656" restart -D "C:\Program Files\PostgreSQL\14\data"
Output:
waiting for server to shut down.... done
server stopped
waiting for server to start....2022-04-28 19:35:46.007 PKT [884] LOG: redirecting log output to logging collector process
2022-04-28 19:35:46.007 PKT [884] HINT: Future log output will appear in directory "log".
done
server started
You can see in the output how the server is first shut down because it is already running, then it is restarted and logged for any changes during its session.
Use SERVICES.MSC
to START/STOP
a PostgreSQL Session in Windows
We already know that a PostgreSQL server is instantiated on your PC
when you launch it, either from PSQL
or PGADMIN
. We can do a few things in SERVICES.MSC
For STOPPED
or PAUSED
services, the Windows Services Manager.
-
Press Windows+R and type in
SERVICES.MSC
. -
Once the Windows Services Manager has opened, search for the PostgreSQL server service in the list. It may be named as follows:
postgresql-x64-14 - PostgreSQL Server 14
. -
Right-click on this to either
START
,STOP
,PAUSE
,RESUME
, orRESTART
your server. You can even change the startup time toAUTOMATIC
for it to start by itself the next time.
The Services Manager also tends to tell us the cause of the failure of a specific service. To view the executable path, you can open the General
tab and view it as follows.
Initiate the PostgreSQL Server From the COMMAND PROMPT
Using NET START
We can use the NET START
command to start a service from the command prompt. The syntax is as follows.
You may need to find the SERVICE_NAME
for your PostgreSQL session. It is also mentioned in the General
tab.
Now you can issue a command as follows.
net start postgresql-x64-14;
This will boot up our server and display output as follows.
Output:
The postgresql-x64-14 - PostgreSQL Server 14 service is starting.
The postgresql-x64-14 - PostgreSQL Server 14 service was started successfully.
However, remember that COMMAND PROMPT
needs to be started as an ADMINISTRATOR
and not a normal user.
Right-click on the CMD.EXE
executable file and click Run as Administrator
. Else you will get an error as follows.
Output:
System error 5 has occurred.
Access is denied.
So today, we learned how to start a PostgreSQL server on Windows in different ways. We hope you read through this article carefully and can use it per your needs.
PostgreSQL is an advanced, freely available, and highly stable relational database management system that offers numerous features, such as accuracy, integrity, resilience, etc. The Postgres database is widely used for storing data of web apps, mobile apps, analytical apps, etc. However, to attain any Postgres features, you must know how to start, stop, or restart a Postgres Server.
To tackle such scenarios, Postgres offers different methods, such as the “pg_ctl” utility, “services” manager, etc. This post presents a practical guide on how to start, stop, or restart the PostgreSQL server on the Windows Operating System.
How Do I Start the Postgres Server?
There are various ways to start the Postgres server on Windows, such as using the “net start” command, “pg_ctl” utility, or “services” manager.
Method 1: Starting Postgres Server Using “net start”
Launch the Windows CMD as an administrator and execute the “net start” command to start the Postgres Server:
net start postgresql-x64-15
Method 2: Starting Postgres Server Using “pg_ctl”
Firstly, you need to find the directory’s path where Postgres is located. If you didn’t change the default path while installing Postgres, then it must be located in the “Program Files” directory inside the “C” drive.
The complete path will look something like this: “C:\Program Files\PostgreSQL\15\data”:
Once you find the complete path, open the CMD and execute the following command to “start the Postgres Server”:
pg_ctl -D "C:\Program Files\PostgreSQL\15\data" start
Note: Windows Path for Postgres tools must be set to get the error-free output. Else you will encounter a “not recognized as an internal/external command” error.
Method 3: Starting Postgres Server Using Services Manager
Press the “win” key + “R” to launch the “Run” window. Type the “services.msc” and hit the “OK” button to open the Services Manager:
In the “Services Manager”, search for “Postgresql-x64-15”, select the service, and hit the “Start/play” button to start a Postgres server via the “services” manager:
Once you press the “start” button the service’s status will be changed to “running”:
How to Stop the Postgres Server on Windows?
A Postgres server can be stopped using the “net stop” command, the “pg_ctl” utility, or the “services” manager.
Method 1: Stopping the Postgres Server Using “net stop”
Execute the below-mentioned command from the Command prompt to stop the Postgres Server:
net stop postgresql-x64-15
Method 2: Stopping the PostgreSQL Server via the “pg_ctl”
Users may use the “pg_ctl” utility to stop the Postgres server:
pg_ctl -D "C:\Program Files\PostgreSQL\15\data" stop
Method 3: Stopping the Postgres Server Using the Services Manager
Open the “Services Manager”, search for “Postgresql-x64-15”, select the service, and hit the “Stop” button to stop a Postgres server via the “services” manager:
Clicking on the “Stop” button will stop the Postgres Server.
Note: Similarly, to pause a Postgres Server on Windows, you can select the “pause” button from the Services manager or execute the “net pause postgresql-x64-15” command from the command prompt.
How Do I Restart the Postgres Server on Windows?
You can restart the Postgres server on the windows operating system using the “Services” Manager and “pg_ctl” utility.
Method 1: Restarting the Postgres Server via the “pg_ctl”
Run the below-given command from the CMD to restart the Postgres Server:
pg_ctl -D "C:\Program Files\PostgreSQL\15\data" restart
Method 2: Restarting the Postgres Server Using the Services Manager
Launch the “Services Manager”, locate the “Postgresql-x64-15”, select the desired service, and hit the “restart” button to restart a Postgres server via the “services” manager:
Clicking on the Restart button will restart the Postgres Server.
Conclusion
There are various ways to start, stop, or restart the Postgres server on Windows, such as using the “net start” command, “pg_ctl” utility, or “services” manager. To get the error-free output, Windows Path for Postgres tools must be set. Else you will encounter a “not recognized as an internal/external command” error. This post presented a practical guide on how to start, stop, or restart the PostgreSQL server on the windows operating system.
Внедрение надёжной и эффективной системы управления базами данных (СУБД) – ключевой аспект в современном мире информационных технологий. PostgreSQL, одна из наиболее мощных и масштабируемых открытых СУБД, пользуется заслуженным признанием среди специалистов по базам данных. В данной статье вы найдёте основные шаги по установке PostgreSQL на виртуальный выделенный сервер, работающий на Windows Server 2016.
Дистрибутив PostgreSQL под Windows доступен для загрузки на своей официальной странице.
После завершения загрузки дистрибутива на ваш сервер запустите скачанный установщик. В его стартовом окне нажмите Next
.
На следующем шаге укажите каталог, в который будет произведена установка. Либо оставьте каталог, предложенный по умолчанию.
Далее выберите компоненты, предназначенные для установки. По умолчанию выбор активирован для всех компонентов.
На следующем шаге укажите каталог, в котором будут храниться данные PostgreSQL. Так же, как и ранее, вы можете оставить директорию, предложенную по умолчанию, и нажать Next
.
После чего система попросит вас ввести пароль администратора, который впоследствии понадобится вам для подключения к СУБД.
Далее укажите порт, по которому в дальнейшем вы сможете подключаться к СУБД. По умолчанию система предлагает к использованию порт под номером 5432.
На следующем шаге выберите язык, который будет использоваться в интерфейсе PostgreSQL. Вы так же можете оставить значение по умолчанию и нажать Next
.
В итоговом окне установщик покажет настройки, выбранные вами для инсталляции. В том числе здесь указан путь к директории, в которую установлена СУБД, номер порта, имя суперпользователя СУБД.
Наконец, для запуска непосредственно процесса установки PostgreSQL нажмите Next
.
После завершения инсталляции нажмите Finish
. При этом если вы оставите активной галочку в заключительном окне установщика, то запустится инсталляция Stack Builder. Данная утилита используется для загрузки и установки дополнительных инструментов, драйверов и приложений, и нужна для завершении инсталляции PostgreSQL.
Установка Stack Builder
Сначала необходимо будет выбрать установленную версию PostgreSQL.
Далее выберите приложение, предназначенное для установки. В нашем примере мы проинсталлируем пакет PEM-HTTPD – предварительно сконфигурированный веб-сервер Apache, скомпилированный для использования с PostgreSQL.
Затем выберите или оставьте предложенный по умолчанию каталог для загрузки пакета PEM-HTTPD.
Для завершения установки Stack Builder нажмите кнопку Следующий
. Если вы не будете активировать опцию Skip Installation
, то визард запустит инсталляцию пакета PEM-HTTPD.
Установка PEM-HTTPD
В стартовом окне мастера установки PEM-HTTPD нажмите Next
.
Далее – Next
, если вы не изменяете каталог установки пакета.
В следующем окне визард попросит вас указать номер порта, по которому будет доступен веб-сервер. Если вы согласны со значением, предложенным по умолчанию, то также нажмите Next
.
Следующее окно сообщает, что всё готово к установке. Нажмите Next
.
По окончании установки нажмите Finish
.
После чего также завершите установку Stack Builder, нажав Завершить
.
Запуск PostgreSQL
Для запуска интерфейса PostgreSQL нажмите кнопку Пуск
, после чего перейдите PostgreSQL 15
→ pgAdmin 4
.
При подключении СУБД попросит вас набрать пароль, который вы вводили на одном из шагов при установке PostgreSQL.
В итоге откроется интерфейс pgAdmin – популярный графический инструмент для работы с СУБД PostgreSQL. Он предоставляет собой удобный и интуитивно понятный интерфейс для выполнения различных задач, связанных с управлением и администрированием баз данных PostgreSQL. PgAdmin может значительно облегчить работу с PostgreSQL, особенно для тех, кто предпочитает графический интерфейс или не любит вводить SQL-команды напрямую.