Postgresql как открыть базу данных
Перейти к содержимому

Postgresql как открыть базу данных

  • автор:

PostgreSQL – Connect and Access a Database

In this article, we will learn about how to access the PostgreSQL database. Once the database is created in PostgreSQL, we can access it in two ways using:

  • psql:PostgreSQL interactive terminal program, which allows us to interactively enter, edit, and execute SQL commands.
  • pgAdmin: A graphical frontend web-based tool, suite with ODBC or JDBC support to create and manipulate a database.

Connect and Access PostgreSQL Database Server using psql:

A psql is an interactive terminal program provided by the PostgreSQL installer. It allows us to interact with the PostgreSQL database server to perform/execute SQL statements and manage database objects.

Step 1: Launch SQL Shell (psql) program tool.

SQL Shell psql program tool

It will open a command window like below where we need to provide details of Server, Database, Port, Username, and Password.

Step 2: To use the default value specified in the square bracket [ ], just press Enter and move on to the next line. While entering the password for user Postgres, we need to enter the password that we set during the PostgreSQL installation.

Step 3: Now, interact with the database server using SQL commands.

Step 4: Using the’ select version();’ command, it will print the current version details of PostgreSQL. Below are some of the commands to interact with the PostgreSQL database.

Step 5: The psql program supports a number of internal commands that are not SQL commands. They begin with the backslash character, “\”. Type \? at the psql prompt to get these commands.

Connect and Access PostgreSQL Database Server using pgAdmin:

This is the other way to access a database is by using the pgAdmin application. The pgAdmin is a web-based front-end application that allows interacting with the PostgreSQL database server via an intuitive user interface.

Step 1: Launch the ‘pgAdmin’ application.

pgAdmin application

It will open the below application where we can create databases, tables and execute queries accordingly.

Step 2: By default, PostgreSQL has a database named ‘Postgres’. We can create Schemas, Tables, Triggers, etc. We can also create our own database in the PostgreSQL server.

Step 3: Under the Tools section, we can use Query Tool to query the database.

Step 4: We can run SQL commands to query the database like below.

We can access the PostgreSQL database using ‘psql’ tool or the ‘pgAdmin’ application. Other than these, we can also connect to the database by writing a custom application, using one of the several available language bindings that support ODBC or JDBC like Python, Java, etc.

Postgresql как открыть базу данных

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

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

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:

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:

The last line could also be:

That would mean you are a database superuser, which is most likely the case if you installed the PostgreSQL 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:

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 PostgreSQL SQL commands by typing:

To get out of psql , type:

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.

Prev Up Next
1.3. Creating a Database Home Chapter 2. The SQL Language

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

Данная статья относится к циклу статей, посвященных PostgreSQL. В предыдущей статье мы узнали о том, как установить PostgreSQL для изучения и практики в вашей локальной системе. Теперь мы покажем вам, как подключиться к серверу баз данных PostgreSQL.

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

Подключение к серверу баз данных PostgreSQL через psql#

psql — это интерактивная терминальная программа, предоставляемая PostgreSQL. Она позволяет вам взаимодействовать с сервером баз данных PostgreSQL, например, выполнять операторы SQL и управлять объектами баз данных.

Следующие шаги показывают, как подключиться к серверу баз данных PostgreSQL через программу psql:

Во-первых, запустите программу psql и подключитесь к PostgreSQL Database Server с помощью пользователя postgres, нажав на иконку psql, как показано ниже:

Во-вторых, введите необходимую информацию, такую как сервер, база данных, порт, имя пользователя и пароль. Нажмите Enter, чтобы принять значения по-умолчанию. В любом случае вам нужно ввести пароль, который вы указали во время установки.

В-третьих, попробуйте повзаимодействовать с сервером баз данных PostgreSQL при помощи операторов SQL. Для этого вы можете воспользоваться следующим оператором:

Пожалуйста, не забудьте завершить команду точкой с запятой (;). После нажатия Enter, psql вернёт текущую версию PostgreSQL, установленную в вашей системе.

Подключение к серверу PostgreSQL через pgAdmin#

Вторым способом подключения к базе данных является использование приложения pgAdmin, благодаря которому вы можете взаимодействовать с сервером баз данных PostgreSQL через интуитивно понятный пользовательский интерфейс.

Далее мы покажем, как подключиться к базе данных, используя приложение с графическим интерфейсом pgAdmin.

Во-первых, запустите приложение pgAdmin.

Приложение pgAdmin 4 будет запущено в веб-браузере, как показано на картинке ниже:

Во-вторых, для создания сервера, щёлкните правой кнопкой мыши по узлу Servers и выберите меню Create > Server…

В-третьих, введите имя сервера, например, PostgreSQL и нажмите на вкладку Connection:

В-четвёртых, введите имя хоста и пароль для пользователя postgres, после чего щёлкните по кнопке Save:

В-пятых, щёлкните по узлу Servers, чтобы открыть иерархию сервера. Изначально, PostgreSQL содержит базу данных, которая называется postgres, как показано ниже:

В-шестых, откройте инструмент запросов, выбрав пункт меню Tool > Query Tool или нажав на иконку молнии.

В-седьмых, введите запрос в Query Editor, затем нажмите на кнопку Execute, после чего вы увидите результат запроса, отображающийся во вкладке DataOutput:

Подключение к серверу баз данных PostgreSQL через другие приложения#

Любое приложение, поддерживающее ODBC или JDBC, может подключиться к серверу баз данных PostgreSQL. К тому же, если вы разрабатываете приложение, которое использует соответствующий драйвер, оно также сможет подключиться к серверу баз данных PostgreSQL.

Замечательно! Вы научились подключаться к серверу баз данных PostgreSQL, используя различные клиентские инструменты, такие как psql и pgADMIN. Следующим шагом мы ознакомимся с примером базы данных PostgreSQL, которую вы сможете использовать для изучения и практики.

How to Create a PostgreSQL Database and Tables in 3 Minutes

Francisco Luna

For this tutorial. I assume that you have already installed Postgres and pgAdmin. If that’s not the case you can download them from here.

Open pgAdmin and the Query Tool

Every time you open pgAdming, it will ask for the master password so you can access all your databases. On the column on the left, click on Server > Local Postgres > Databases > postgres. This is a Postgres instance that is created when you install it.

After you have clicked on Postgres database, you have to open the query tool. Using this tool, you can write all your SQL statements.

Once opened, on the right side, a text editor will open for writing SQL commands. The Scratch Pad is used to hold text or scripts only.

Creating a Database and Tables

To create a database, we need to run the following command:

Here, we are using two SQL keywords. The first one is the CREATE statement, and the second one DATABASE. The third word is the name of the database that we are creating. It is good practice to write the SQL keywords in upper case.

Always remember to add the semicolon at the end. Though some commands will run without a problem even if you don’t add it, it is a standard in SQL.

Tip: To run the commands on the query tool, you can press F5 or click the Execute/Refresh button in the top menu.

Before creating anything in our new database, we need to ensure that we are running our scripts in the new database. For this, go to the left panel and right click on the database. Then, click on Refresh. Now, the name of our new database will…

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *