> For the complete documentation index, see [llms.txt](https://tobyisme.gitbook.io/gitlab/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://tobyisme.gitbook.io/gitlab/zi-liao-ku-shi-yong-fang-5f0f28-postgresql.md).

# 資料庫使用方式(postgreSQL)

## ![](/files/-LxPa5PMjgudro-eHwPl)

## 如何在CentOS 7上安裝和使用PostgreSQL

#### 介紹 <a href="#introduction" id="introduction"></a>

關係數據庫管理系統是許多網站和應用程序的關鍵組成部分。它們提供了一種結構化的方式來存儲，組織和訪問信息。

**PostgreSQL**或Postgres是一個關係型數據庫管理系統，提供SQL查詢語言的實現。它是許多小型和大型項目的受歡迎的選擇，並且具有符合標準的優點，並具有許多高級功能，如可靠的事務和並發性，無需讀鎖。

在本指南中，我們將演示如何在CentOS 7上安裝Postgres，並介紹一些使用它的基本方法。

### 安裝 <a href="#installation" id="installation"></a>

CentOS的默認存儲庫包含Postgres軟件包，因此我們可以使用`yum`軟件包系統來安裝它們而不用麻煩。

安裝postgresql-server包和“contrib”包，增加了一些額外的實用程序和功能：

```java
$ sudo yum install postgresql-server postgresql-contrib
```

接受提示，通過響應a`y`。

現在安裝了我們的軟件，我們必須執行幾個步驟才能使用它。

創建一個新的PostgreSQL數據庫集群：

```
$ sudo postgresql-setup initdb
```

默認情況下，PostgreSQL不允許密碼認證。我們將通過編輯其基於主機的身份驗證（HBA）配置來進行更改。

使用自己喜歡的文本編輯器打開HBA配置。我們將使用vi：

```
$ sudo vi /var/lib/pgsql/data/pg_hba.conf
```

在文件底部附近找到這樣的行：

pg\_hba.conf摘錄（原文）

```
host    all             all             127.0.0.1/32            ident

host    all             all             ::1/128                 ident
```

然後用“md5”替換“ident”，所以他們看起來像這樣：

pg\_hba.conf摘錄（更新）

```
host    all             all             127.0.0.1/32            md5

host    all             all             ::1/128                 md5
```

保存並退出。PostgreSQL現在配置為允許密碼認證。

現在啟動並啟用PostgreSQL：

```
$ sudo systemctl start postgresql
$ sudo systemctl enable postgresql
```

PostgreSQL現在可以使用了。我們可以了解它如何工作，以及它可能與您可能已經使用的類似數據庫管理系統有所不同。

### 使用PostgreSQL角色和數據庫 <a href="#using-postgresql-roles-and-databases" id="using-postgresql-roles-and-databases"></a>

默認情況下，Postgres使用一個名為“roles”的概念來幫助認證和授權。這些在某些方麵類似於常規的Unix風格的帳戶，但Postgres並不區分用戶和組，而是更喜歡更靈活的術語“角色”。

安裝後Postgres設置為使用“ident”身份驗證，這意味著它將Postgres角色與匹配的Unix / Linux系統帳戶相關聯。如果存在Postgres角色，則可以通過登錄相關的Linux系統帳戶登錄。

安裝過程創建了一個`postgres`與默認的Postgres角色相關聯的用戶帳戶。為了使用Postgres，我們需要登錄該帳戶。您可以輸入以下內容：

```
$ sudo -i -u postgres
```

您將被要求您的正常用戶密碼，然後將為用戶提供一個shell提示符`postgres`。

您可以輸入以下內容立即獲得Postgres提示：

```
$ psql
```

您將自動登錄，並可以立即與數據庫管理系統進行交互。

但是，我們將要解釋一下如何使用其他角色和數據庫，以便您對要使用的用戶和數據庫有一定的靈活性。

鍵入以下內容退出PostgreSQL提示符：

```
postgres=# \q
```

您現在應該回到`postgres`用戶命令提示符。

### 創造新角色 <a href="#create-a-new-role" id="create-a-new-role"></a>

從`postgres`Linux帳戶，您可以登錄數據庫系統。但是，我們還將演示如何創建其他角色。`postgres`與Postgres管理角色相關聯的Linux帳戶可以訪問一些實用程序來創建用戶和數據庫。

我們可以通過鍵入以下方式創建新角色：

```
$ createuser --interactive
```

這基本上是一個交互式shell腳本，調用正確的Postgres命令來創建一個用戶的規範。它只會問你兩個問題：角色的名稱以及它是否應該是超級用戶。通過傳遞一些附加標誌可以獲得更多的控制權。通過查看`man`頁面查看選項：

```
$ man createuser
```

### 創建一個新的數據庫 <a href="#create-a-new-database" id="create-a-new-database"></a>

默認情況下設置Postgres（認證由匹配的系統帳戶請求的角色）的方式也假設要存在要連接的角色的匹配數據庫。

所以如果我有一個用戶被調用`test1`，該角色將嘗試連接到`test1`默認調用的數據庫。

您可以通過簡單地以該`postgres`用戶身份調用此命令來創建相應的數據庫：

```
$ createdb test1
```

### 使用新用戶連接到Postgres <a href="#connect-to-postgres-with-the-new-user" id="connect-to-postgres-with-the-new-user"></a>

我們假設你有一個Linux系統帳戶被調用`test1`（你可以通過鍵入來創建一個`sudo adduser test1`），並且你已經創建了一個Postgres角色和數據庫`test1`。

您可以通過鍵入以下內容更改為Linux系統帳戶：

```
$ sudo -i -u test1
```

然後，您可以通過鍵入以下內容`test1`與`test1`Postgres角色連接到數據庫：

```
$ psql
```

假設已經配置了所有組件，這將自動登錄。

如果您希望用戶連接到其他數據庫，可以通過指定數據庫（請確保您`\q`到命令提示符）來執行此操作：

```
$ psql -d postgres
```

您可以輸入以下內容，獲取有關您登錄的Postgres用戶以及當前連接到的數據庫的信息：

```
postgres=# \conninfo
```

```
Output:
You are connected to database "postgres" as user "postgres" via socket in "/var/run/postgresql" at port "5432".
```

如果要連接到非默認數據庫或非默認用戶，這可以幫助您提醒您當前的設置。

### 列出數據庫 <a href="#create-a-new-database" id="create-a-new-database"></a>

您可以使用`\l`or`\list`命令列出所有數據庫。

```
postgres=# \l
```

```
List of databases
Name    |  Owner   | Encoding |   Collate   |    Ctype    |   Access privileges
-----------+----------+----------+-------------+-------------+-----------------------
mytestdb  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
postgres  | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 |
template0 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
|         |          |          |             | postgres=CTc/postgres
template1 | postgres | UTF8     | en_US.UTF-8 | en_US.UTF-8 | =c/postgres          +
|         |          |          |             | postgres=CTc/postgres
(4 rows)
```

### 創建和刪除表 <a href="#create-and-delete-tables" id="create-and-delete-tables"></a>

現在你知道如何連接到PostgreSQL數據庫系統，我們將開始如何完成一些基本的任務。

首先，我們創建一個表來存儲一些數據。讓我們創建一個描述遊樂設備的表格。

這個命令的基本語法是這樣的：

```
postgres=# CREATE TABLE table_name (
postgres=#     column_name1 col_type (field_length) column_constraints,
postgres=#     column_name2 col_type (field_length),
postgres=#     column_name3 col_type (field_length)
postgres=# );
```

如您所見，我們給表一個名稱，然後定義我們想要的列，以及字段數據的列類型和最大長度。我們還可以選擇為每列添加表約束。

您可以[在](https://digitalocean.com/community/articles/how-to-create-remove-manage-tables-in-postgresql-on-a-cloud-server)這裡了解有關[如何在Postgres中創建和管理表格的](https://digitalocean.com/community/articles/how-to-create-remove-manage-tables-in-postgresql-on-a-cloud-server)更多信息。

為了我們的目的，我們將要創建一個簡單的表：

```
postgres=# CREATE TABLE playground (
postgres=#     equip_id serial PRIMARY KEY,
postgres=#     type varchar (50) NOT NULL,
postgres=#     color varchar (25) NOT NULL,
postgres=#     location varchar(25) check (location in ('north', 'south', 'west', 'east', 'northeast', 'southeast', 'southwest', 'northwest')),
postgres=#     install_date date
postgres=# );
```

我們製作了一個操作台，清理我們所擁有的設備。這是從`serial`類型的設備ID開始的。該數據類型是自動遞增整數。我們給出了這個列的約束，`primary key`這意味著值必須是唯一的，而不是null。

對於我們的兩個列，我們沒有給出一個字段長度。這是因為一些列類型不需要設置長度，因為該類型的長度是隱含的。

然後，我們給出設備類型和顏色的列，每個列不能為空。然後，我們創建一個位置列，並創建一個約束，該約束需要該值為八個可能的值之一。最後一列是記錄我們安裝設備的日期的日期列。

我們可以通過鍵入以下方式看到我們的新表：

```
postgres=# \d
```

```
Output:
                   List of relations

 Schema |          Name           |   Type   |  Owner   

--------+-------------------------+----------+----------

 public | playground              | table    | postgres

 public | playground_equip_id_seq | sequence | postgres

(2 rows)
```

正如你所看到的，我們有我們的操場表，但是我們也有一些叫做`playground_equip_id_seq`類型的東西`sequence`。這是我們給我們的`equip_id`列的“連續”類型的表示。這跟踪序列中的下一個數字。

如果要查看表格，可以輸入：

```
postgres=# \dt
```

```
Output:
           List of relations

 Schema |    Name    | Type  |  Owner   

--------+------------+-------+----------

 public | playground | table | postgres

(1 row)
```

### 在表中添加，查詢和刪除數據 <a href="#add-query-and-delete-data-in-a-table" id="add-query-and-delete-data-in-a-table"></a>

現在我們創建了一個表，我們可以在其中插入一些數據。

我們添加一個幻燈片和一個鞦韆。我們通過調用我們想要添加的表來命名列，然後為每列提供數據來做到這一點。我們的幻燈片和鞦韆可以這樣添加：

```
postgres=# INSERT INTO playground (type, color, location, install_date) VALUES ('slide', 'blue', 'south', '2014-04-28');
postgres=# INSERT INTO playground (type, color, location, install_date) VALUES ('swing', 'yellow', 'northwest', '2010-08-16');
```

你應該注意一些事情。首先，請記住，列名不應該被引用，但是您輸入的列*值*需要引號。

要記住的另一件事是，我們不輸入`equip_id`列的值。這是因為當表中的新行被創建時，這是自動生成的。

然後，我們可以通過鍵入以下信息獲取我們添加的信息：

```
postgres=# SELECT * FROM playground;
```

```
Output:
 equip_id | type  | color  | location  | install_date 

----------+-------+--------+-----------+--------------

        1 | slide | blue   | south     | 2014-04-28

        2 | swing | yellow | northwest | 2010-08-16

(2 rows)
```

在這裡，您可以看到我們`equip_id`已經成功填寫，並且我們所有的其他數據已正確組織。

如果我們的幻燈片斷開，我們將其從操場上移除，我們還可以通過鍵入以下命令從表中刪除該行：

```
postgres=# DELETE FROM playground WHERE type = 'slide';
```

如果我們再次查詢我們的表，我們將看到我們的幻燈片不再是表的一部分：

```
postgres=# SELECT * FROM playground;
```

```
Output:
 equip_id | type  | color  | location  | install_date 

----------+-------+--------+-----------+--------------

        2 | swing | yellow | northwest | 2010-08-16

(1 row)
```

### 如何從表中添加和刪除列 <a href="#how-to-add-and-delete-columns-from-a-table" id="how-to-add-and-delete-columns-from-a-table"></a>

如果我們要在創建表之後修改一個表以添加一個附加列，那麼我們可以輕鬆地做到這一點。

我們可以添加一列以顯示每件設備的最後一次維護訪問，方法是鍵入以下內容：

```
postgres=# ALTER TABLE playground ADD last_maint date;
```

如果您再次查看表信息，您將看到已添加新列（但未輸入任何數據）：

```
postgres=# SELECT * FROM playground;
```

```
Output:
 equip_id | type  | color  | location  | install_date | last_maint 

----------+-------+--------+-----------+--------------+------------

        2 | swing | yellow | northwest | 2010-08-16   | 

(1 row)
```

我們可以輕鬆刪除列。如果我們發現我們的工作人員使用一個單獨的工具來跟踪維護歷史，我們可以通過鍵入以下命令來擺脫列：

```
postgres=# ALTER TABLE playground DROP last_maint;
```

### 如何更新表中的數據 <a href="#how-to-update-data-in-a-table" id="how-to-update-data-in-a-table"></a>

我們知道如何向表中添加記錄以及如何刪除它們，但是我們還沒有介紹如何修改現有條目。

您可以通過查詢所需記錄來更新現有條目的值，並將列設置為要使用的值。我們可以查詢“擺動”記錄（這將匹配我們表中的*每個*擺動），並將其顏色更改為“紅色”。如果我們給它一個油漆工作，這可能是有用的：

```
postgres=# UPDATE playground SET color = 'red' WHERE type = 'swing';
```

我們可以通過再次查詢我們的數據來驗證操作是否成功：

```
postgres=# SELECT * FROM playground;
```

```
Output:
 equip_id | type  | color | location  | install_date 

----------+-------+-------+-----------+--------------

        2 | swing | red   | northwest | 2010-08-16

(1 row)
```

如您所見，我們的幻燈片現在已註冊為紅色。

### 結論 <a href="#conclusion" id="conclusion"></a>

您現在在CentOS 7服務器上設置了PostgreSQL。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://tobyisme.gitbook.io/gitlab/zi-liao-ku-shi-yong-fang-5f0f28-postgresql.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
