Как установить postgresql linux mint

Работаем с PostgreSQL через командную строку в Linux

Установка PostgreSQL на Linux (Mint)

Для подключения к базе данных PostgreSQL понадобится установленный PostgreSQL клиент:

Для установки PostgreSQL сервера:

Проверим, можем ли мы подключиться к базе данных PostgreSQL:

Вывод команды должен быть примерно таким:

PostgreSQL Подключение, Пользователи (Роли) и Базы Данных

Логин в только что установленный postgreSQL сервер нужно производить под именем пользователя postgres:

Для подключения к базе данных PostgreSQL можно использовать команду:

Если такая команда не просит ввести пароль пользователя, то можно еще добавить опцию -W.

После ввода пароля и успешного подключения к базе данных PostgreSQL, можно посылать SQL-запросы и psql-команды.

PostgreSQL создание новой роли и базы данных

Создать новую роль c именем admin (указывайте нужное имя):

Создание новой базы данных:

Дать права роли на базу данных:

Включить удаленный PostgreSQL доступ для пользователей

Нам нужно отредактировать файл /etc/postgresql/ /main/pg_hba.conf, задав опцию md5 вместо peer.

может быть 10, 11, 12 и т.д.

После этого сделать restart PostgreSQL:

Полезные команды PostgreSQL

Выйти из клиента PostgreSQL:

\q

Показать список баз данных PostgreSQL:

\l

Показать список таблиц:

\dt

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

\du

Показать структуру таблицы:

Переименовать базу данных:

Удалить базу данных:

Изменить текущую базу данных в PostgreSQL (вы не сможете переименовать или удалить текущую базу данных):

\connect db_name или более короткий alias: \c db_name

Удалить роль (пользователя):

Роль не будет удалена, если у нее есть привелегии — возникнет ошибка ERROR: role cannot be dropped because some objects depend on it .

Нужно удалить привелегии у роли, например если нужно удалить роль admin2, нужно выполнить последовательность комманд с Drop Owned:

Дать права пользователю/роли на логин ( role is not permitted to log in ):

Выбор shema psql в консоли:

Посмотреть список всех схем:

Подключиться к конкретной схеме:

Sequences

Получить имена всех созданных sequences:

Получить последнее значение sequence, которые будет присвоено новой вставляемой в таблицу записи:

Источник

Как установить PostgreSQL с pgAdmin4 на Linux Mint 20

pgAdmin — это многофункциональный инструмент управления интерфейсом с открытым исходным кодом. Который позволяет легко администрировать и управлять реляционной базой данных PostgreSQL из веб-браузера.

Читайте также:  Windows 10 mobile как установить appx

Он обеспечивает простой в использовании пользовательский интерфейс, который упрощает создание и мониторинг баз данных, а так же объектов базы данных. PgAdmin 4 является улучшением более раннего инструмента pgAdmin и доступен для систем Linux, Windows, macOS.

В этой статье вы узнаете, как установить PostgreSQL с помощью pgAdmin4 на Linux Mint 20.

Шаг 1: Установите базу данных PostgreSQL на Linux Mint

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

После завершения обновления перейдите к следующему шагу.

Поскольку pgAdmin4 предоставляет интерфейс frontend для управления объектами базы данных PostgreSQL. Очень важно сначала установить PostgreSQL.

2. Для этого требуется установить пакет postgresql и postgresql-contrib, который предлагает расширение функций PostgreSQL.

$ sudo apt install postgresql postgresql-contrib

3. Обычно PostgreSQL запускается автоматически при загрузке. Вы можете подтвердить это с помощью приведенной ниже команды:

$ sudo systemctl status postgresql

4. Чтобы войти в PostgreSQL, для начала переключитесь на пользователя postgres. Пользователь Postgres входит в комплект поставки по умолчанию вместе с установкой PostgreSQL. Затем выполните команду psql, как показано на рисунке.

5. Кроме того, вы можете проверить, принимает ли сервер базы данных входящие соединения.

Шаг 2: Установите pgAdmin4 на Linux Mint

pgAdmin4 доступен для Ubuntu 16.04 и более поздних версий. Он его можно установить с помощью APT package manager. Разработчики Pgadmi4 еще не включили поддержку Linux Mint позволяющую пользователям легко устанавливать инструмент управления фронтендом с помощью APT package manager.

6. Единственный жизнеспособный вариант — это установить pgAdmin4 из виртуальной среды. Итак, для начала мы установим необходимые пакеты, как показано на рисунке.

$ sudo apt install libgmp3-dev build-essential libssl-dev

7. Затем установите виртуальную среду Python и связанные с ней зависимости.

$ sudo apt install python3-virtualenv python3-dev libpq-dev

8. Далее создайте каталог, в котором вы будете создавать виртуальную среду.

9. Затем создайте виртуальную среду, как показано ниже. Здесь pgadmin4env — это имя виртуальной среды.

10. Как только виртуальная среда установлена, активируйте ее, как показано ниже.

11. Затем требуется использовать инструмент pip для установки pgadmin4.

12. Далее создайте файл конфигурации config_local.py.

$ sudo nano pgadmin4env/lib/python3.8/site-packages/pgadmin4/config_local.py

И добавьте в этот файл строки которые написаны ниже.

import os
DATA_DIR = os.path.realpath(os.path.expanduser(u’

/.pgadmin/’))
LOG_FILE = os.path.join(DATA_DIR, ‘pgadmin4.log’)
SQLITE_PATH = os.path.join(DATA_DIR, ‘pgadmin4.db’)
SESSION_DB_PATH = os.path.join(DATA_DIR, ‘sessions’)
STORAGE_DIR = os.path.join(DATA_DIR, ‘storage’)
SERVER_MODE = False

13. Чтобы запустить средство управления pgAdmin4, вызовите команду:

14. Теперь, перейдите в свой браузер и введите адрес указанный ниже.

Вам будет предложено установить мастер-пароль, поэтому установите надежный пароль и нажмите кнопку «ОК«.

Установить Пароль PgAdmin4

15. Чтобы упростить задачу, вы можете создать алиас (псевдоним) в файле

/.bashrc, как показано ниже.

16. Затем обновите файл bashrc.

17. Ну и теперь наконец вы можете запустить инструмент управления pgAdmin4, просто вызвав команду startpg.

Еще раз зайдите в свой браузер и войдите в интерфейс PgAdmin4. На этом установка pgAdmin4 в Linux Mint завершается.

Источник

How to Install PostgreSQL with pgAdmin4 on Linux Mint 20

pgAdmin is an open-source feature-rich, frontend management tool that allows you to easily administer and manage your PostgreSQL relational database from a web browser.

Читайте также:  Драйвера для hd5450 для windows

It provides an easy-to-use user interface that simplifies the creation and monitoring of databases and database objects. PgAdmin 4 is an improvement of the earlier pgAdmin tool and is available for Linux, Windows, macOS systems, and even a Docker container.

In this tutorial, you will learn how to install PostgreSQL with pgAdmin4 on Linux Mint 20.

Step 1: Install PostgreSQL Database on Linux Mint

1. To start off, launch your terminal and update your packages using the apt package manager as shown.

Once the update is complete, proceed to the next step.

Since pgAdmin4 provides a frontend interface for the management of PostgreSQL database objects, it’s essential to have PostgreSQL installed first.

2. To do this, we are going to install the postgresql package and postgresql-contrib which offers extended features that extend the functionality of PostgreSQL.

Install PostgreSQL on Linux Mint

3. Usually, PostgreSQL starts automatically on boot up. You can confirm this using the command given below:

Check PostgreSQL Status

4. To log in to your PostgreSQL instance, first switch to the postgres user. The Postgres user comes included by default with the installation of PostgreSQL. Then run the psql command as shown.

Connect to PostgreSQL Shell

5. Additionally, you can check if the database server is accepting incoming connections as shown.

Check PostgreSQL Accepting Incoming Connections

Step 2: Install pgAdmin4 on Linux Mint

pgAdmin4 is available for Ubuntu 16.04 and later versions and can easily be installed using the APT package manager. The same cannot support Linux Mint 20 and Pgadmi4 developers are yet to include support that allows users to easily install the frontend management tool using the APT package manager.

6. The only viable option is to install pgAdmin4 from a virtual environment. So first, we will install the prerequisite packages as shown.

Install Prerequisite Packages

7. Next, install the Python virtual environment and associated dependencies.

Install Python Virtual Environment

8. Next, create a directory where you will create a virtual environment.

9. Then create the virtual environment as shown. Here, pgadmin4env is the name of the virtual environment.

Create Virtual Environment for pgAdmim4

10. Once the virtual environment is in place, activate it as shown.

11. Then use the pip tool to install pgadmin4 as shown.

Install PgAdmin4 in Linux Mint

12. Next, create a configuration file config_local.py.

and add the lines below.

Create PgAdmin4 Configuration

13. To start the pgAdmin4 management tool, invoke the command:

Start PgAdmin4 Service

14. Finally, head over to your browser and browse the address shown.

You will be prompted to set the master password, so proceed and set a strong password and click the ‘Ok’ button.

Set PgAdmin4 Password

15. To make things easier, you can create an alias in the

Читайте также:  Отключить повышенную безопасность windows 2012

/.bashrc file as shown.

16. Next, update the bashrc file.

17. Finally, you can start the pgAdmin4 management tool by simply invoking the startpg command.

Start PgAdmin4 Tool

Once again head over to your browser and log in to the PgAdmin4 interface. And this concludes the installation of pgAdmin4 on Linux Mint.

If You Appreciate What We Do Here On TecMint, You Should Consider:

TecMint is the fastest growing and most trusted community site for any kind of Linux Articles, Guides and Books on the web. Millions of people visit TecMint! to search or browse the thousands of published articles available FREELY to all.

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

We are thankful for your never ending support.

Источник

How to Install PostgreSQL Server on Linux Mint 20

Hello everyone, in this article I will guide you on how to install PostgreSQL Server on Linux Mint 20. Linux Mint 20 is a great Linux desktop but we can also use it for server use. Installing PostgreSQL Server is pretty much easy. I have been using PostgreSQL Server to store my spatial database. The PostGIS extension is very helpful for GIS professionals. It supports many GIS software such as MapInfo Professional, QGIS, Global Mapper, and many more. Please check out my GIS Tutorial website for more articles about GIS.

Steps to Install PostgreSQL Server on Linux Mint 20

First, we need to update our system using apt update command. This will ensure we have the latest package available for the installation.

Next, lets install Postgresql server with this command

Wait until the installation process completes. Now make sure the service is up and running.

Next, let’s try to login to the Postgresql Server.

and run the psql command

Now you are entering the Postgresql console. To exit, type

Done. At this point, you have successfully installed Postgresql Server on Linux Mint 20. Now let’s create a new user.

Create a new user (role)

The command will create a new user called dhani with password 12345. You can modify it for your own purposes.

Change postgres user password

By default, postgres user does not have a password. We can create a new one

Create a new database

The command will create a new database called gis.

Enable Remote Access to PostgreSQL Server

If you want the server to be accessible from the network, you will need to edit the configuration files below.

pg_hba.conf

Add the following line to the pg_hba.conf file. This will allow the server to be accessed from anywhere, including the internet. Change it accordingly if you want something else.

Add this line to it

Now restart the server

So that’s is. Thanks for reading this tutorial to install PostgreSQL Server on Linux Mint.

Источник

Оцените статью