Как создать базу данных postgresql linux
The first test to see whether you can access the database server is to try to create a database. A running PostgreSQL server can manage many databases. Typically, a separate database is used for each project or for each user.
Possibly, your site administrator has already created a database for your use. In that case you can omit this step and skip ahead to the next section.
To create a new database, in this example named mydb , you use the following command:
If this produces no response then this step was successful and you can skip over the remainder of this section.
If you see a message similar to:
then PostgreSQL was not installed properly. Either it was not installed at all or your shell’s search path was not set to include it. Try calling the command with an absolute path instead:
The path at your site might be different. Contact your site administrator or check the installation instructions to correct the situation.
Another response could be this:
This means that the server was not started, or it is not listening where createdb expects to contact it. Again, check the installation instructions or consult the administrator.
Another response could be this:
where your own login name is mentioned. This will happen if the administrator has not created a PostgreSQL user account for you. ( PostgreSQL user accounts are distinct from operating system user accounts.) If you are the administrator, see Chapter 22 for help creating accounts. You will need to become the operating system user under which PostgreSQL was installed (usually postgres ) to create the first user account. It could also be that you were assigned a PostgreSQL user name that is different from your operating system user name; in that case you need to use the -U switch or set the PGUSER environment variable to specify your PostgreSQL user name.
If you have a user account but it does not have the privileges required to create a database, you will see the following:
Not every user has authorization to create new databases. If PostgreSQL refuses to create databases for you then the site administrator needs to grant you permission to create databases. Consult your site administrator if this occurs. If you installed PostgreSQL yourself then you should log in for the purposes of this tutorial under the user account that you started the server as. [1]
You can also create databases with other names. PostgreSQL allows you to create any number of databases at a given site. Database names must have an alphabetic first character and are limited to 63 bytes in length. A convenient choice is to create a database with the same name as your current user name. Many tools assume that database name as the default, so it can save you some typing. To create that database, simply type:
If you do not want to use your database anymore you can remove it. For example, if you are the owner (creator) of the database mydb , you can destroy it using the following command:
(For this command, the database name does not default to the user account name. You always need to specify it.) This action physically removes all files associated with the database and cannot be undone, so this should only be done with a great deal of forethought.
More about createdb and dropdb can be found in createdb and dropdb respectively.
[1] As an explanation for why this works: PostgreSQL user names are separate from operating system user accounts. When you connect to a database, you can choose what PostgreSQL user name to connect as; if you don’t, it will default to the same name as your current operating system account. As it happens, there will always be a PostgreSQL user account that has the same name as the operating system user that started the server, and it also happens that that user always has permission to create databases. Instead of logging in as that user you can also specify the -U option everywhere to select a PostgreSQL user name to connect as.
Prev | Up | Next |
1.2. Architectural Fundamentals | Home | 1.4. Accessing a Database |
Submit correction
If you see anything in the documentation that is not correct, does not match your experience with the particular feature or requires further clarification, please use this form to report a documentation issue.
Как создать базу данных postgresql linux
Первое, как можно проверить, есть ли у вас доступ к серверу баз данных, — это попытаться создать базу данных. Работающий сервер PostgreSQL может управлять множеством баз данных, что позволяет создавать отдельные базы данных для разных проектов и пользователей.
Возможно, ваш администратор уже создал базу данных для вас. В этом случае вы можете пропустить этот этап и перейти к следующему разделу.
Для создания базы данных, в этом примере названной mydb , выполните следующую команду:
Если вы не увидите никаких сообщений, значит операция была выполнена успешно и продолжение этого раздела можно пропустить.
Если вы видите сообщение типа:
значит PostgreSQL не был установлен правильно. Либо он не установлен вообще, либо в путь поиска команд оболочки не включён его каталог. Попробуйте вызвать ту же команду, указав абсолютный путь:
У вас этот путь может быть другим. Свяжитесь с вашим администратором или проверьте, как были выполнены инструкции по установке, чтобы исправить ситуацию.
Ещё один возможный ответ:
Это означает, что сервер не работает или createdb не может к нему подключиться. И в этом случае пересмотрите инструкции по установке или обратитесь к администратору.
Также вы можете получить сообщение:
где фигурирует ваше имя пользователя. Это говорит о том, что администратор не создал учётную запись PostgreSQL для вас. (Учётные записи PostgreSQL отличаются от учётных записей пользователей операционной системы.) Если вы сами являетесь администратором, прочитайте Главу 22, где написано, как создавать учётные записи. Для создания нового пользователя вы должны стать пользователем операционной системы, под именем которого был установлен PostgreSQL (обычно это postgres ). Также возможно, что вам назначено имя пользователя PostgreSQL , не совпадающее с вашим именем в ОС; в этом случае вам нужно явно указать ваше имя пользователя PostgreSQL , используя ключ -U или установив переменную окружения PGUSER .
Если у вас есть учётная запись пользователя, но нет прав на создание базы данных, вы увидите сообщение:
Создавать базы данных разрешено не всем пользователям. Если PostgreSQL отказывается создавать базы данных для вас, значит вам необходимо соответствующее разрешение. В этом случае обратитесь к вашему администратору. Если вы устанавливали PostgreSQL сами, то для целей этого введения вы должны войти в систему с именем пользователя, запускающего сервер БД. [1]
Вы также можете создавать базы данных с другими именами. PostgreSQL позволяет создавать сколько угодно баз данных. Имена баз данных должны начинаться с буквы и быть не длиннее 63 символов. В качестве имени базы данных удобно использовать ваше текущее имя пользователя. Многие утилиты предполагают такое имя по умолчанию, так что вы сможете упростить ввод команд. Чтобы создать базу данных с таким именем, просто введите:
Если вы больше не хотите использовать вашу базу данных, вы можете удалить её. Например, если вы владелец (создатель) базы данных mydb , вы можете уничтожить её, выполнив следующую команду:
(Эта команда не считает именем БД по умолчанию имя текущего пользователя, вы должны явно указать его.) В результате будут физически удалены все файлы, связанные с базой данных, и так как отменить это действие нельзя, не выполняйте его, не подумав о последствиях.
Узнать о командах createdb и dropdb больше можно в справке createdb и dropdb .
[1] Объяснить это поведение можно так: Учётные записи пользователей PostgreSQL отличаются от учётных записей операционной системы. При подключении к базе данных вы можете указать, с каким именем пользователя PostgreSQL нужно подключаться. По умолчанию же используется имя, с которым вы зарегистрированы в операционной системе. При этом получается, что в PostgreSQL всегда есть учётная запись с именем, совпадающим с именем системного пользователя, запускающего сервер, и к тому же этот пользователь всегда имеет права на создание баз данных. И чтобы подключиться с именем этого пользователя PostgreSQL , необязательно входить с этим именем в систему, достаточно везде передавать его с параметром -U .
PostgreSQL
PostgreSQL is a powerful object-relational database management system, provided under a flexible BSD-style license. [1] PostgreSQL contains many advanced features, is very fast and standards compliant.
PostgreSQL has bindings for many programming languages such as C, C++, Python, Java, PHP, Ruby. It can be used to power anything from simple web applications to massive databases with millions of records.
Client Installation
If you only wish to connect to an external PostgreSQL server, do not install the main PostgreSQL package, but install the PostgreSQL client package instead. To do this, use the following command
you then connect to the server with the following command
After you inserted the password you access PostgreSQL with line commands. You may for instance insert the following
You exit the connection with
Installation
To install the server locally use the command line and type:
This will install the latest version available in your Ubuntu release and the commonly used add-ons for it.
See "External Links" below for options for getting newer releases.
Installing PostGIS, procedural languages, client interfaces, etc
Additional packages contain procedural language runtimes, add-ons like PostGIS, language client interfaces like psycopg2 for Python, etc. You can get a listing with:
Administration
pgAdmin III is a handy GUI for PostgreSQL, it is essential to beginners. To install it, type at the command line:
You may also use the Synaptic package manager from the System>Administration menu to install these packages.
Basic Server Setup
To start off, we need to set the password of the PostgreSQL user (role) called "postgres"; we will not be able to access the server externally otherwise. As the local “postgres” Linux user, we are allowed to connect and manipulate the server using the psql command.
In a terminal, type:
this connects as a role with same name as the local user, i.e. "postgres", to the database called "postgres" (1st argument to psql).
Set a password for the "postgres" database role using the command:
and give your password when prompted. The password text will be hidden from the console for security purposes.
Type Control+D or \q to exit the posgreSQL prompt.
Create database
To create the first database, which we will call "mydb", simply type:
Install Server Instrumentation (for PgAdmin) for Postgresql 8.4 or 9.3
PgAdmin requires the installation of an add-on for full functionality. The "adminpack" addon, which it calls Server Instrumentation, is part of postgresql-contrib, so you must install that package if you haven’t already:
Then to activate the extension, for ""Postgresql 8.4"", run the adminpack.sql script, simply type:
For "Postgresql 9.3"+ install the adminpack "extension" in the "postgres" database:
Alternative Server Setup
If you don’t intend to connect to the database from other machines, this alternative setup may be simpler.
By default in Ubuntu, Postgresql is configured to use ‘ident sameuser’ authentication for any connections from the same machine. Check out the excellent Postgresql documentation for more information, but essentially this means that if your Ubuntu username is ‘foo’ and you add ‘foo’ as a Postgresql user then you can connect to the database without requiring a password.
Since the only user who can connect to a fresh install is the postgres user, here is how to create yourself a database account (which is in this case also a database superuser) with the same name as your login name and then create a password for the user:
Client programs, by default, connect to the local host using your Ubuntu login name and expect to find a database with that name too. So to make things REALLY easy, use your new superuser privileges granted above to create a database with the same name as your login name:
Connecting to your own database to try out some SQL should now be as easy as:
Creating additional database is just as easy, so for example, after running this:
You can go right ahead and tell Amarok to use postgresql to store its music catalog. The database name would be amarokdb, the username would be your own login name, and you don’t even need a password thanks to ‘ident sameuser’ so you can leave that blank.
Using pgAdmin III GUI
To get an idea of what PostgreSQL can do, you may start by firing up a graphical client. In a terminal type :
You will be presented with the pgAdmin III interface. Click on the "Add a connection to a server" button (top left). In the new dialog, enter the address 127.0.0.1 (Local host is default, so it can be left out.), a description of the server, the default database ("mydb" in the example above), your username ("postgres") and your password. One more step is required in order to allow pgAdmin III to connect to the server, and that is to edit pg_hba.conf file and change the authentication method from peer to md5 (will not work if you have not set the password):
and change the line
Now you should reload the server configuration changes and connect pgAdmin III to your PostgreSQL database server.
With this GUI you may start creating and managing databases, query the database, execute SQl etc.
Managing the Server
To learn more about managing PostgreSQL (but without the Ubuntu specifics) see the official PostgreSQL documentation
Managing users and rights
User management is discussed in detail in the client authentication chapter of the PostgreSQL documentation; the following is an introduction to get you started.
To manage users, you first have to edit /etc/postgresql/current/main/pg_hba.conf and modify the default configuration which is very locked down and secure. For example, if you want postgres to manage its own users (not linked with system users), you will add the following line:
Which means that on your local network (10.0.0.0/24 — replace with your own local network !), postgres users can connect through the network to the database providing a classical couple user / password.
Besides allowing a user to connect over the network to the to a database on the server, you must enable PostgreSQL to listen across different networks. To do that, open up /etc/postgresql/current/main/postgresql.conf in your favourite editor and alter the listen_addresses as below:
to listen on all network interfaces. See the docs for listen_addresses for other options.
To create a database with a user that have full rights on the database, use the following command:
The first command line creates the user with no database creation rights (-D) with no add user rights -A) and will prompt you for entering a password (-P). The second command line create the database ‘mydb with ‘myuser‘ as owner.
This little example will probably suit most of your needs. For more details, please refer to the corresponding man pages or the online documentation.
restarting the server
After configuring the networking / users you may need to reload the server, here is a suggested command to do so.
Some settings changes in postgresql.conf require a full restart, which will terminate active connections and abort uncommitted transactions:
Further reading
If you are not familiar with SQL you may want to look into this powerful language, although some simple uses of PostgreSQL may not require this knowledge (such as a simple Django project).
The PostgreSQL website contains a wealth of information on using this database. In particular, the tutorial is a useful starting point, but you can skip the installation step as you’ve already installed it using Ubuntu packages.
Troubleshooting
fe_sendauth: no password supplied
Your pg_hba.conf specifies that md5 authentication is to be used for this connection based on the origin host, connection method and the requested username/database, but your application didn’t supply a password.
Change the authentication mode or set a password for the user you’re connecting to and then specify that password in your application’s connection settings.
FATAL: role "myusername" does not exist
By default PostgreSQL connects to the PostgreSQL user with the same name as the current unix user. You have not created a PostgreSQL user by that name in your database.
Create a suitable user, or specify a different username to connect with. In the command line tools the -U flag does this.
FATAL: database "myusername" does not exist
A user named "myusername" exists, but there’s no database of the same name.
By default PostgreSQL connects to the database with the same name as the user you’re connecting as, but it doesn’t auto-create the database if it doesn’t exist.
Create the database, or specify a different database to connect to.
FATAL: Peer authentication failed for user "myusername"
You are connecting to localhost via a unix socket. A user named "myusername" exists, but your current unix user is not the same as that username. PostgreSQL is set to use "peer" authentication on unix sockets for this user/db combo so it requires your unix and postgresql usernames to match.
Connect from the unix user that matches the desired PostgreSQL user — perhaps with sudo -u theusername psql — or change pg_hba.conf to use a different authentication mode like "md5" for this username.
could not connect to server: No such file or directory
An error like this (possibly with a different unix socket path, depending on your install):
can mean a number of things:
* The server isn’t running;
* The server has a different unix_socket_directories to the default in your client’s libpq, either due to different compiled-in defaults or a mismatched setting;
* The server is listening on a different "port". PostgreSQL emulates TCP/IP ports on unix sockets by using the port number as the suffix for the socket file, e.g. 5432.
Eliminate these in turn.
First make sure the server is running. On Ubuntu, ps -u postgres -f will show you any processes running as user postgres — you want to see multiple ones named postgres.
Now make sure the server is listening where your client thinks it is. To find out your PostgreSQL server’s socket directory:
or on older PostgreSQL versions, unix_socket_directory as the parameter changed name. To show the server’s port (which applies for both TCP/IP and unix sockets):
If you can’t even connect with psql under unix user postgres you can check the socket dir with lsof:
In this case the first line is the socket location. This server has socket directory /tmp with port 5432.
If your client is looking in a different socket directory, you’re probably trying to connect over unix sockets to the default socket path and/or to the default port, and the libpq your client application is linked to has a different compiled-in unix socket path and/or port than your running PostgreSQL. Most likely your LD_LIBRARY_PATH or /etc/ld.so.conf has a different libpq before the one that came with your version of PostgreSQL. This doesn’t generally matter much, you can just override the socket directory.
To specify an alternative socket directory and/port port to connect to, specify the socket dir as the host parameter in your connection options, e.g. to connect as user bob to the server listening in /tmp on port 5433:
or in connection-string form:
The same works with any client that uses libpq (all the PostgreSQL client tools, plus e.g. psycopg2, the Pg gem in Ruby/Rails, PHP’s postgres and PDO, Perl’s DBB::Pg, etc). It does NOT work with non-libpq clients like PgJDBC, py-postgresql, etc, but most of these don’t support unix sockets at all. See the client documentation for non-libpq based clients.
[1] You do not have to pay in order to use PostgreSQL for any application, such as commercial closed source software. See http://www.postgresql.org/about/licence/.
External Links
Official PostgreSQL downloads
The PostgreSQL project provides an official list of download locations, including an Ubuntu software repository, at its download page. In particular, Ubuntu users can get newer PostgreSQL versions than those packaged in their Ubuntu release using apt-get via apt.postgresql.org.
For support and services around PostgreSQL see the services and support page.
EnterpriseDB
The PostgreSQL Linux downloads page contains a section on "Graphical installer" built by EnterpriseDB. You download the installer, change its properties to allow to run it as command (it has .run extension), and run it from command prompt as in "sudo whateveritwas.run".
- configured DB server instance, which starts with your server
- pgAdmin III UI client application
Note that the installed software will not be integrated with Ubuntu software center. As a result, you will not receive any security updates from Ubuntu. However, the installed version will closely match the latest Ubuntu version.
Turnkey Linux
An Ubuntu-based PostgreSQL appliance is one of the easiest ways to get up and running with PostgreSQL on Ubuntu. It’s part of a family of pre-integrated TurnKey Linux Software Appliances based on Ubuntu 10.04.1 (Lucid LTS).
PostgreSQL (последним исправлял пользователь x1-6-10-5f-49-81-52-90 2015-08-28 13:16:48)
The material on this wiki is available under a free license, see Copyright / License for details
You can contribute to this wiki, see Wiki Guide for details
Работа с базой данных PostgreSQL
PostgreSQL – опенсорсная реляционная СУБД. Отличается гибкостью и надежностью, поддерживает большое количество полезных возможностей. Часто используется в проектах, где требуется работа со сложными структурами данных, с которыми не справляются простые СУБД.
В этой статье мы разберемся, как работать с PostgreSQL. В качестве примера я буду использовать Ubuntu 18.04.
Установка PostgreSQL
PostgreSQL есть в репозитории Ubuntu, поэтому установка выполняется одной командой. Но сначала нужно проверить обновления самой системы:
Для выполнения команды нужны права суперпользователя. Так что придется вспомнить пароль.
После установки апдейтов инсталлируем PostgreSQL:
PostgreSQL установится вместе с пакетом contrib, в котором содержится дополнительная функциональность, а также утилиты для работы СУБД.
Чтобы убедиться, что все работает, проверим версию:
При установке автоматически создается роль и пользователь postgres.
Настройка PostgreSQL
Работать с PostgreSQL мы будем через терминал с помощью встроенной утилиты psql. Запускаем ее следующей командой:
Можно установить сторонние инструменты для администрирования PostgreSQL, но в этом мало смысла — psql справляется со всеми основными задачами.
Чтобы получить поддержку, вводим в терминале команду:
Если нужна справка по конкретной команде, пишем:
Выйти из psql можно командой \q.
Управление пользователями
В PostgreSQL используется концепция ролей. Одну роль можно рассматривать как отдельного пользователя или как группу пользователей. Роли могут владеть объектами БД и выдавать разрешения другим ролям.
По умолчанию была создана роль postgres. Давайте создадим еще одну роль. Для этого и з консоли системы выполняем команду:
Система запросит имя для новой роли, пароль, а также позволит настроить привилегии — например, нужно ли давать права суперпользователя или разрешать создавать другие роли и базы данных.
Если вы уже зашли в psql, то создать новую роль можно командой:
Затем задаем пароль:
Вывести список всех ролей можно командой /du. Кроме имен отобразятся привилегии каждого роли.
Чтобы закрыть список ролей, выполняем команду q.
Для удаления пользователя выполняем команду:
Это можно также сделать из консоли системы с помощью команды:
Чтоб сменить пароль пользователя, подключаемся к psql с правами суперпользователя. Затем выполняем следующую команду:
Эта операция сохраняется в файле .psql_history вместе с паролем, который не будет зашифрован. В качестве дополнительной меры безопасности эту запись рекомендуется удалить. Файл обычно находится в директории /var/lib/postgresql.
Работа с базами данных в PostgreSQL
Создать базу данных из консоли можно следующей командой:
Если вы используете терминальный клиент psql, то команда будет немного отличаться:
Чтобы посмотреть список всех БД, выполняем команду \l.
Для удаления базы данных используется та же команда, что и для удаления роли — drop. В терминале системы синтаксис будет таким:
В клиенте psql синтаксис похожий:
Подключение к базе данных
По умолчанию psql подключается от имени текущего пользователя Linux к БД с таким же названием. Если эти данные совпадают, достаточно выполнить запуск самого терминального клиента:
Чтобы вывести информацию о текущем соединении, выполняем команду:
Если имя базы данных отличается от имени пользователя, нужно указать его явно:
Если имя роли не совпадает с именем пользователя в Linux, прописываем дополнительные параметры.
Имя роли и название БД совпадают:
Название базы данных отличается от имени роли:
Чтобы переключиться на другую базу данных внутри psql используем команду:
Создание резервной копии и восстановление из бэкапа
Для создания резервной копии базы данных используется сложная команда:
Чтобы было проще разобраться, рассмотрим каждый параметр:
- хост – сервер, на котором располагается БД. Например, можно указать localhost, домен, IP-адрес.
- имя_роли – имя пользователя PostgreSQL, под которым мы работаем с базой данных.
- формат_дампа – формат, в котором дамп сохранится на сервере. Доступны следующие форматы: c (custom) – архив .tar.gz, t (tar) – архив .tar, p (plain) – текст без сжатия, обычно .sql.
- путь_к_дампу – путь, по которому будет сохранена резервная копия.
- имя_БД – название БД, для которой будет создана резервная копия.
Выглядит это примерно так:
Для выполнения этой команды нужно ввести пароль, который используется при входе в psql от имени указанной роли (mybase в приведенном примере).
Восстановление из резервной копии выполняется аналогичным образом:
Параметры похожие, отличия минимальные. Важно знать хост, помнить формат и путь к бэкапу.
Мы разобрались с основными действиями и настройками PostgreSQL. На этом все!