安装
在 Mac 上安装PostgreSQL
的方式有很多,我选择了使用Homebrew
,配上国内源,速度飞起,很快就可以安装好了。Homebrew
国内源,我选择了清华大学的TUNA社区开源镜像。
替换现有
Homebrew
上游:1
2
3
4
5
6
7
8
9cd "$(brew --repo)"
git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/brew.git
cd "$(brew --repo)/Library/Taps/homebrew/homebrew-core"
git remote set-url origin https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/homebrew-core.git
brew update替换
Homebrew
二进制预编译包的镜像:1
2
3echo 'export HOMEBREW_BOTTLE_DOMAIN=https://mirrors.tuna.tsinghua.edu.cn/homebrew-bottles' >> ~/.bash_profile
source ~/.bash_profile安装
PostgreSQL
:1
brew install postgresql
等待安装完成。
启动数据库
PostgreSQL
数据库安装好之后,创建一个文件夹用于以后存放数据。我在用户根路径创建了一个 PostgreSQL
文件夹及其子文件夹 data
。然后配置环境变量 PGDATA
, 把它加到 bash_profile
文件中。
1 | export PGDATA= "/Users/abo/PostgreSQL/data" |
然后命令行进入 data
子文件夹,执行命令 initdb
来初始化数据库,初始化完成之后会提示数据库启动命令。
执行命令启动数据库1
pg_ctl -D /Users/abo/PostgresSQL/data -l logfile start
数据库相关操作
查看当前所有数据库, 默认会有3个数据库
postgres
、template0
、template1
1
psql -l
进入目标数据库
1
psql postgres
创建用户,注意数据库命令后面有个分号,大小写都可以
1
create user abo login superuser with password '666';
创建数据库
1
CREATE DATABASE db_test OWNER abo;
删除数据库
1
drop database db_test;
创建表
1
create table user_tbl(id bigint, name varchar(10), age int, height real);
插入数据
1
insert into user_tbl (id, name, age, height) values(123456, 'abo', 25, 170.0);
更多数据库命令可以使用命令 \h
查看或到下载手册。
中文手册地址:http://www.postgres.cn/docs/9.3/index.html
数据类型
名字 | 别名 | 描述 |
---|---|---|
bigint | int8 | 有符号8字节整数 |
bigserial | serial8 | 自增8字节整数 |
bit [ (n) ] | 定长位串 | |
bit varying [ (n) ] | varbit | 可变长位串 |
boolean | bool | 逻辑布尔值(真/假) |
box | 平面上的矩形 | |
bytea | 二进制数据(“字节数组”) | |
character varying [ (n) ] | varchar [ (n) ] | 可变长字符串 |
character [ (n) ] | char [ (n) ] | 定长字符串 |
cidr | IPv4 或 IPv6 | 网络地址 |
circle | 平面上的圆 | |
date | 日历日期(年, 月, 日) | |
double precision | float8 | 双精度浮点数(8字节) |
inet | IPv4 或 IPv6 | 主机地址 |
integer | int, int4 | 有符号 4 字节整数 |
interval [ fields ] [ (p) ] | 时间间隔 | |
line | 平面上的无限长直线 | |
lseg | 平面上的线段 | |
macaddr | MAC (Media Access Control)地址 | |
money | 货币金额 | |
numeric [ (p, s) ] decimal [ (p, s) ] | 可选精度的准确数值数据类型 | |
path | 平面上的几何路径 | |
point | 平面上的点 | |
polygon | 平面上的封闭几何路径 | |
real | float4 | 单精度浮点数(4 字节) |
smallint | int2 | 有符号 2 字节整数 |
smallserial | serial2 | 自增 2 字节整数 |
serial | serial4 | 自增 4 字节整数 |
text | 可变长字符串 | |
time [ (p) ] [ without time zone ] | 一天中的时刻(无时区) | |
time [ (p) ] with time zone | timetz | 一天中的时刻,含时区 |
timestamp [ (p) ] [ without time zone ] | 日期与时刻(无时区) | |
timestamp [ (p) ] with time zone | timestamptz | 日期与时刻,含时区 |
tsquery | 文本检索查询 | |
tsvector | 文本检索文档 | |
txid_snapshot | 用户级别的事务ID快照 | |
uuid | 通用唯一标识符 | |
xml | XML 数据 | |
json | JSON 数据 |