1.4. Подключение к базе данных #

Создав базу данных, вы можете обратиться к ней:

  • Запустив терминальную программу Postgres Pro под названием psql, в которой можно интерактивно вводить, редактировать и выполнять команды SQL.

  • Используя существующие графические инструменты, например, pgAdmin или офисный пакет с поддержкой ODBC или JDBC, позволяющий создавать и управлять базой данных. Эти возможности здесь не рассматриваются.

  • Написав собственное приложение, используя один из множества доступных языковых интерфейсов. Подробнее это рассматривается в Части IV.

Чтобы работать с примерами этого введения, начните с psql. Подключиться с его помощью к базе данных mydb можно, введя команду:

$ psql mydb

Если имя базы данных не указать, она будет выбрана по имени пользователя. Об этом уже рассказывалось в предыдущем разделе, посвящённом команде createdb.

В psql вы увидите следующее сообщение:

psql (16.8.1)
Type "help" for help.

mydb=>

Последняя строка может выглядеть и так:

mydb=#

Что показывает, что вы являетесь суперпользователем, и так скорее всего будет, если вы устанавливали экземпляр Postgres Pro сами. В этом случае на вас не будут распространяться никакие ограничения доступа, но для целей данного введения это не важно.

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

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

mydb=> SELECT pgpro_version();
                                         version
-------------------------------------------------------------------​-----------------------
 PostgresPro 16.8.1 on x86_64-pc-linux-gnu, compiled by gcc (Debian 4.9.2-10) 4.9.2, 64-bit
(1 row)

mydb=> SELECT current_date;
    date
------------
 2016-01-07
(1 row)

mydb=> SELECT 2 + 2;
 ?column?
----------
        4
(1 row)

В программе psql есть множество внутренних команд, которые не являются SQL-операторами. Они начинаются с обратной косой черты, «\». Например, вы можете получить справку по различным SQL-командам Postgres Pro, введя:

mydb=> \h

Чтобы выйти из psql, введите:

mydb=> \q

и psql завершит свою работу, а вы вернётесь в командную оболочку операционной системы. (Чтобы узнать о внутренних командах, введите \? в приглашении командной строки psql.) Все возможности psql документированы в справке psql. В этом руководстве мы не будем использовать эти возможности явно, но вы можете изучить их и применять при удобном случае.

1.4. Accessing a Database #

Once you have created a database, you can access it by:

  • Running the Postgres Pro interactive terminal program, called psql, which allows you to interactively enter, edit, and execute SQL commands.

  • Using an existing graphical frontend tool like pgAdmin or an office suite with ODBC or JDBC support to create and manipulate a database. These possibilities are not covered in this tutorial.

  • Writing a custom application, using one of the several available language bindings. These possibilities are discussed further in Part IV.

You probably want to start up psql to try the examples in this tutorial. It can be activated for the mydb database by typing the command:

$ psql mydb

If you do not supply the database name then it will default to your user account name. You already discovered this scheme in the previous section using createdb.

In psql, you will be greeted with the following message:

psql (16.8.1)
Type "help" for help.

mydb=>

The last line could also be:

mydb=#

That would mean you are a database superuser, which is most likely the case if you installed the Postgres Pro instance yourself. Being a superuser means that you are not subject to access controls. For the purposes of this tutorial that is not important.

If you encounter problems starting psql then go back to the previous section. The diagnostics of createdb and psql are similar, and if the former worked the latter should work as well.

The last line printed out by psql is the prompt, and it indicates that psql is listening to you and that you can type SQL queries into a work space maintained by psql. Try out these commands:

mydb=> SELECT pgpro_version();
                                         version
-------------------------------------------------------------------​-----------------------
 PostgresPro 16.8.1 on x86_64-pc-linux-gnu, compiled by gcc (Debian 4.9.2-10) 4.9.2, 64-bit
(1 row)

mydb=> SELECT current_date;
    date
------------
 2016-01-07
(1 row)

mydb=> SELECT 2 + 2;
 ?column?
----------
        4
(1 row)

The psql program has a number of internal commands that are not SQL commands. They begin with the backslash character, \. For example, you can get help on the syntax of various Postgres Pro SQL commands by typing:

mydb=> \h

To get out of psql, type:

mydb=> \q

and psql will quit and return you to your command shell. (For more internal commands, type \? at the psql prompt.) The full capabilities of psql are documented in psql. In this tutorial we will not use these features explicitly, but you can use them yourself when it is helpful.