postgresql學習(一)

一.postgresql介紹

官網
https://www.postgresql.org/
官方相關文檔
http://www.postgres.cn/v2/document

二.安裝postgresql

安裝版本9.6.11
版本庫:
https://www.postgresql.org/ftp/source/

#下載源碼包:
cd /usr/local/src/
wget https://ftp.postgresql.org/pub/source/v9.6.11/postgresql-9.6.11.tar.gz

#解壓
tar -zxvf postgresql-9.6.11.tar.gz 

#編譯安裝
cd postgresql-9.6.11
./configure   //默認會安裝到/usr/local/pgsql目錄
#會提示需要安裝依賴包
yum install -y readline-devel
yum install -y zlib-devel

#再次編譯
./configure

#安裝
make && make install

配置postgresql所需環境:

#創建用戶
adduser postgres

#創建數據目錄
mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data

#初始化
su - postgres
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data >logfile 2>&1 &

#配置環境變量
vim /etc/profile
#添加
PATH=$PATH:/usr/local/pgsql/bin
#退出,執行
source /etc/profile

三.postgresql的使用

1.首先是登入,登入的方式有兩種,一種是指定用戶名登入:

psql -U postgres 

另一種是切換到postgres用戶下去登入:

[root@ligen src]# su postgres
bash-4.2$ psql 

2.創建和刪除數據庫:

createdb -U postgres db1
dropdb -U postgres db1

3.登入後提示說明:
在這裏插入圖片描述

四.增刪查改

和mysql的操作類似
先來創建兩個表,來支持後續是操作:

#創建表t1
create table t1(city varchar(30),temp_lo int,temp_hi int,prcp real,date date);
real:單精度浮點型
date:時間類型

#創建表t2
create table t2(name varchar(30),location point);
point:空間數據類型

1.insert(增)

#方法一:全字段
insert into t1 values ('shijiazhuang',15,25,0.25,'1997-07-09');
#方法二:指定字段
insert into t1(city,temp_lo,temp_hi) values ('nanchang',15,25);

2.select(查)

select * from t1;
select city,temp_lo from t1;

select city,(temp_hi+temp_lo)/2 AS temp_avg,date from t1;
select * from t1 where city = 'nanchang';
select * from t1 where city = 'nanchang' order by city;

3.update(改)

update t1 set city = 'beijing',temp_lo=temp_lo-2 where city='nanchang';

5.delete(刪)

delete from t1 where city = 'beijing';

其他常用命令:

列出所有數據庫:

\l

切換數據庫:

\c 數據庫名稱
\c test

列出當前數據庫所有的表:

\d

列出表結構:

\d 表名稱
\d t1;

列出詳細的表結構:

\d+ t1;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章