> For the complete documentation index, see [llms.txt](https://sphantix-hang.gitbook.io/timebook/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sphantix-hang.gitbook.io/timebook/2.-huan-jing-pian/kai-fa-huan-jing-pei-zhi/tong-yong/postgre_sql.md).

# PostgreSQL安装与使用

`PostgreSQL`是开源的关系型数据库。

## 一、安装

## 1.1 Mac OS

`Mac OS`使用`homebrew`安装，在`shell`中输入`brew search postgresql`，得到以下输出:

```bash
==> Formulae
postgresql                    postgresql@11                 postgresql@9.5
postgresql@10 ✔               postgresql@9.4                postgresql@9.6
==> Casks
navicat-for-postgresql
```

选择需要安装的版本即可，`@`后为版本号，例如`brew install postgresql@10`安装`PostgreSQL 10`。

### 1.2 Linux

todo

### 1.3 Windows

todo

## 二、配置

### 2.1 Mac OS

如果安装的不是最新版本，则需要自行添加环境变量，以`Postgre 10`为例，需要添加以下环境变量：

```bash
export PATH="/usr/local/opt/postgresql@10/bin:$PATH"
export LDFLAGS="-L/usr/local/opt/postgresql@10/lib"
export CPPFLAGS="-I/usr/local/opt/postgresql@10/include"
export PKG_CONFIG_PATH="/usr/local/opt/postgresql@10/lib/pkgconfig"
```

在添加完成后，在`shell`中输入`brew services`，检查`PostgreSQL`是否运行，如果没有运行，需要运行`PostgreSQL`服务。以`Postgre 10`为例，`shell`输入`brew services start postgresql@10`即可启动服务。

### 2.2 Linux

todo

### 2.3 Windows

todo

## 三、使用

1. `createdb <dbname>`创建数据库；
2. `psql <dbname>`进入数据库控制台；
3. 使用`\password <pass>`为`postgreSQL`用户设置密码；
4. 使用`create user <username>`创建数据库用户；
5. 创建表，用法如下：

   ```sql
    reate table <tablename> (
        column1 datatype,
        column2 datatype,
        column3 datatype,
        .....
        columnN datatype,
        PRIMARY KEY( 一个或多个列 )
    );
   ```
6. 使用`grant all privileges on <tablename> to <username>`将表的所有权限都赋给某用户。
7. todo...
