1. 程式人生 > 遊戲 >美少女三消遊戲《Mirror 2: Project X》上架Steam 提前開啟搶測

美少女三消遊戲《Mirror 2: Project X》上架Steam 提前開啟搶測

Postgresql

中文文件:http://www.postgres.cn/docs/13/

手冊下載:https://github.com/postgres-cn/pgdoc-cn/releases

PostgreSQL是以加州大學伯克利分校計算機系開發的物件關係型資料庫管理系統(ORDBMS),免費開源。

docker安裝PostgreSQL

docker run -d --name=postgres --restart=always -e POSTGRES_PASSWORD='password' -e ALLOW_IP_RANGE=0.0.0.0/0 -v ~/postgres/data:/var/lib/postgresql -p 5432:5432 postgres:12.8

# 進入容器
docker exec -it postgres bash

終端操作

進入終端

# 使用其他作業系統使用者登入 postgresql資料庫互動終端
root@9ad0ef6c0ed5:/# psql -Upostgres
psql (12.8 (Debian 12.8-1.pgdg100+1))
Type "help" for help.

# #表示的當前使用者是超級管理員,$表示其他普通管理員
postgres=#

元命令

文件:http://www.postgres.cn/docs/13/app-psql.html#APP-PSQL-META-COMMANDS

元命令 描述
? 檢視所有終端操作符
\q 退出終端
\l 列出伺服器中的資料庫並且顯示它們的名稱、擁有者、字符集編碼以及訪問特權。\list也可以
\c <資料庫名> 切換進入資料庫
\dt 列出當前資料庫中所有資料表
\du 列出系統中所有的使用者角色
\di 列出當前資料庫中所有索引
\h 檢視命令的幫助資訊
\conninfo 輸出有關當前資料庫連線的資訊
\encoding 輸出當前客戶端連線的編碼資訊,\encoding utf8 表示設定編碼
\password [ username ] 給指定使用者設定新的密碼口令

資料庫管理

-- 建立資料庫
-- CREATE DATABASE <資料庫名>;
create database school;
-- 檢視資料庫列表,也可以直接使用 \l
select datname from pg_database;
--                                  List of databases
--    Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
-- -----------+----------+----------+------------+------------+-----------------------
--  postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
--  school    | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
--  template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
--            |          |          |            |            | postgres=CTc/postgres
--  template1 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres          +
--            |          |          |            |            | postgres=CTc/postgres
-- (4 rows)

-- 進入資料庫school
\c school

-- 刪除資料庫
-- DROP DATABASE <資料庫名>;
drop database school;

資料庫模式

PostgreSQL 模式(SCHEMA)可以看著是一個表的集合。一個模式下可以包含多個檢視、索引、資料型別、函式和操作符等。

相同的物件名稱(表名、檢視、索引等)可以被用於不同的模式中而不會出現衝突,例如 模式schema1 和 模式myschema 都可以包含名為 mytable 的表。

使用模式的優勢:

  • 允許多個使用者使用一個數據庫並且不會互相干擾。
  • 將資料庫物件組織成邏輯組以便更容易管理。
  • 第三方應用的資料可以放在獨立的模式中,這樣它們就不會與其他物件的名稱發生衝突。

總而言之,就是使用者的資料可以儲存在同一個資料庫中,但是因為各自處於不同的模式下,所以看到的表結構可以一樣,但是資料是不一樣的。非常適合用於實現許可權隔離、一般在開發中往往用於多租戶系統。

模式類似於我們開發時使用的python虛擬環境。

建立模式

基本語法:

-- 可以使用 CREATE SCHEMA 語句來建立模式
-- CREATE SCHEMA schema_name.mytable (
-- ...
-- );

-- 例子:schema_name 就是模式名稱,但是實際開發,一般都會基於不同的組織、角色、群組來設定模式名稱
create table schema_name.company(
   ID   INT              NOT NULL,
   NAME VARCHAR (20)     NOT NULL,
   AGE  INT              NOT NULL,
   ADDRESS  CHAR (25),
   SALARY   DECIMAL (18, 2),
   PRIMARY KEY (ID)
);

刪除模式

-- 刪除一個為空的模式
DROP SCHEMA myschema;
-- 刪除一個非空的模式
DROP SCHEMA myschema CASCADE;

資料表管理

-- 建立資料表
-- CREATE TABLE <資料表名> (
--    欄位名 資料型別 型別約束 註釋,
--    欄位名 資料型別 型別約束 註釋,
--    ...
--    unique name(name)
-- );
create table student (
   id serial not null primary key,
   name char(15),
   age smallint,
   sex boolean default true,
   mobile char(20) unique,
   money real
);

-- 列出當前資料庫所有資料表,也可以使用 \d
SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';
--                List of relations
--  Schema |      Name      |   Type   |  Owner
-- --------+----------------+----------+----------
--  public | student        | table    | postgres
--  public | student_id_seq | sequence | postgres
-- (2 rows)

-- 查看錶結構,也可以使用-- \d <資料表名>
SELECT column_name,data_type,is_nullable,column_default FROM information_schema.columns WHERE table_name ='student';
--                                Table "public.student"
--  Column |     Type      | Collation | Nullable |               Default
-- --------+---------------+-----------+----------+-------------------------------------
--  id     | integer       |           | not null | nextval('student_id_seq'::regclass)
--  name   | character(15) |           |          |
--  age    | smallint      |           |          |
--  sex    | boolean       |           |          | true
--  mobile | character(20) |           |          |
--  money  | real          |           |          |
-- Indexes:
--     "student_pkey" PRIMARY KEY, btree (id)
--     "student_mobile_key" UNIQUE CONSTRAINT, btree (mobile)

-- 刪除表
-- DROP TABLE <資料表名>;
drop table student;

資料管理

新增資料

-- 新增1條資料
INSERT INTO <資料表名> (欄位1,欄位2,欄位3,...) VALUES (值1, 值2, 值3,...);
-- 新增多條資料
INSERT INTO <資料表名> (欄位1,欄位2,欄位3,...) VALUES (值1, 值2, 值3,...),(值1, 值2, 值3,...),(值1, 值2, 值3,...);

INSERT INTO student (name,age,sex,mobile,money) VALUES ('張小娟', 15, false,'15354929233',1300.00);
INSERT INTO student (name,age,sex,mobile,money) VALUES 
('張小明', 16, true, '15350939483',1100.00),
('張小雨', 15, false,'13312349633',1150.00),
('張娟',   17, true, '15397494555',2350.00),
('張成雨', 17, true, '15512392542',1850.00),
('張瀟雨', 14, false,'13529258339',1450.00),
('張成風', 15, true, '15059229494',1540.00),
('江小白', 16, false,'13669338500',1339.00),
('江浩宇', 16, true, '13939529299',2015.00),
('江浩天', 19, true, '18252242002',1996.00),
('江茗雨', 18, false,'18253293345',1560.00),
('江建宇', 17, true, '15522120421',1702.00),
('江小雨', 17, false,'15368285757',1888.00),
('江小雨', 17, false,'10086111111',1888.00);

基本查詢

-- 查詢所有資料
SELECT * FROM <資料表名>;
-- 查詢所有資料的指定欄位資訊
SELECT <欄位1>,<欄位2>,.... FROM <資料表名>;
-- 查詢符合條件的資料的指定欄位資訊
SELECT <欄位1>,<欄位2>,.... FROM <資料表名> WHERE 條件;

-- 查詢所有學生的所有資訊
select * from student;
-- 查詢出id為偶數的學生資訊
select id,name,mobile from student where id%2=0;
-- 查詢出所有女生的學生資訊
select id,name,mobile from student where sex=false;
-- 查詢出所有15歲以上女生的學生資訊
select id,name,mobile from student where sex=false and age > 15;

刪除資料

-- 刪除符合條件的資料
DELETE FROM <資料表名> WHERE 條件;
-- 清空資料
TRUNCATE TABLE <資料表名>;

-- 刪除mobile = '10086111111'的資料
delete from student where mobile = '10086111111';
-- 清空資料表資料記錄,並重置表狀態
truncate table student;

更新資料

-- 全表更新資料
UPDATE <資料表名> SET 欄位=值,欄位=值,...;
-- 更新符合條件的資料
UPDATE <資料表名> SET 欄位=值 WHERE 條件;

-- 設定所有學生的money為100
update student set money=1000 where money < 0;
-- 給所有學生在原基礎上增加2000塊以內的隨機金額
update student set money=money+ceil(random()*2000);
-- 給所有學生在原基礎上扣除2000塊以內的隨機金額
update student set money=money-ceil(random()*2000);
select id,name,money from student;
-- 給id=1的學生新增100餘額
update student set money=money+100 where id=1;

查詢進階

-- 多表查詢
SELECT * FROM <資料表名1>,<資料表名2>,...;
SELECT <欄位1>,<欄位2>,... FROM <資料表名1>,<資料表名2>,...;

-- 排序顯示資料
SELECT <欄位1>,<欄位2>,... FROM <資料表名> ORDER BY <欄位> DESC,<欄位> ASC,...;

-- 查詢n條資料
SELECT <欄位1>,<欄位2>,... FROM <資料表名> WHERE 條件 LIMIT <n>;

-- 查詢下標s之後的n條資料
SELECT <欄位1>,<欄位2>,... FROM <資料表名> WHERE 條件 OFFSET s LIMIT <n>;

-- 查詢統計
SELECT 聚合函式(欄位) FROM <資料表名>;

-- 單欄位分組統計
SELECT <分組欄位>,聚合函式(<欄位>) FROM <資料表名> group by <分組欄位>;
-- 多欄位分組統計
SELECT <分組欄位1>,<分組欄位2>,...,聚合函式(<欄位>) FROM <資料表名> group by <分組欄位1>,<分組欄位2>,...;

-- 聯合查詢
-- 注意,UNION的每個SELECT語句必須是相同數量的列。列必須有相似的資料型別。同時每個SELECT語句中的列的順序也必須相同。
-- 資料不重複
SELECT <欄位1>,<欄位2>,... FROM <資料表名> UNION SELECT <欄位1>,<欄位2>,... FROM <資料表名>;
-- 資料重複
SELECT <欄位1>,<欄位2>,... FROM <資料表名> UNION ALL SELECT <欄位1>,<欄位2>,... FROM <資料表名>;

-- 子查詢
-- 注意:雖名為子查詢,但不管select,還是delete、update、insert都可用子查詢,原因是資料庫操作中,一切操作都是查詢。
-- SELECT <欄位1>,<欄位2>,.... FROM (SELECT <欄位1>,<欄位2>,....) <臨時表別名>;

-- 查詢所有學生的所有資訊,並以age做倒序排列
select * from student order by age desc;
-- 查詢所有學生的所有資訊,並以age第一倒序,money第二升序
select * from student order by age desc,money asc;
-- 查詢5個學生資訊
select * from student limit 5;
-- 查詢錢最多的6個學生
select * from student order by money desc limit 6;
-- 按錢包餘額,查出排名在4-6名的3個學生資訊
select * from student order by money desc offset 3 limit 3;
-- 查詢出手機號以153或者150開頭的學生資訊,並以手機號升序排序
select id,name,mobile from student where mobile like '153%' or mobile like '150%' order by mobile asc;

-- 統計所有學生人數
select count(id) from student;
-- 統計所有學生人數,並給返回的結果欄位設定欄位別名
select count(id) total from student;

-- 分組統計男女人數
select sex, count(id) from student group by sex;
-- 欄位別名【as可以省略】
select case when sex then '男' else '女' end as sex, count(id) from student group by sex;
-- 統計各個年齡段男女人數
select age,sex, count(id) from student group by age,sex;
-- 統計15歲以上各個年齡段男女人數
select age,sex, count(id) from student  where age > 15 group by age,sex;
-- 統計15歲以上各個年齡段錢包餘額最少的男女生,並剔除money>1500的資訊
select age,sex, min(money) from student  where age > 15 group by age,sex having min(money) <= 1500;

-- 單表操作基本不需要子查詢,這裡僅僅為了演示子查詢的使用。
-- 假設每個學生一個月平均消費800,查詢出15歲以上學生在本月,1個月後,2個月後的餘額。
select money,money-800, money-1600 from (select id,age, money from student where age > 15) table1;

備份還原

# 二進位制備份
# pg_dump -h IP地址 -U賬戶 -d資料庫 -Fc > <檔名.dmp>
pg_dump -Upostgres -dschool -Fc > school.dmp

# 匯出sql表結構, 不包含資料
# pg_dump --verbose --schema-only --db=資料庫名 --file=檔名.sql
pg_dump --verbose --schema-only --db=school --file=./school.sql

# 匯出sql表結構與表資料
# pg_dump -U賬戶名 --column-inserts 資料庫名 > 檔名.sql
pg_dump -U postgres --column-inserts school > ./school.sql

# 二進位制還原
# pg_restore -h IP地址 -U賬戶名 -d資料庫 -Fc <檔名>
pg_restore -Upostgres -dtemplate1 -Fc school.dmp

# SQL還原
# psql -d資料庫名 -U賬戶名 -f 檔名.sql
psql -dschool -Upostgres -f ./school.sql

許可權管理

文件:https://www.shulanxt.com/database/postgresql/postgresql-privileges

建立使用者

CREATE USER <使用者名稱> WITH PASSWORD '<登陸密碼>';

CREATE USER shulanxt WITH PASSWORD 'password';

分配許可權

grant 

voker

Python操作

windows下不能直接通過conda或者pip 的install來安裝postgresql模組。

windows系統下載擴充套件包:https://pypi.org/project/psycopg2/#files

pip install psycopg2

# pip install psycopg
import psycopg2,json
from psycopg2.extras import RealDictCursor

if __name__ == '__main__':
    # 連線資料庫
    conn = psycopg2.connect(database="school", user="postgres", password="password", host="127.0.0.1", port="5432")
    print(conn)
    # 獲取遊標
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    # print(cursor)

    # # """讀取資料"""
    # # 讀取多條資料
    # cursor.execute('select * from student limit 5')
    # rows = cursor.fetchall()
    # for row in rows:
    #     row = dict(row)
    #     print(row["name"], row)
    #
    #     data_str = json.dumps(row,ensure_ascii=False)
    #     print(data_str)

    # # 讀取1條資料
    # cursor.execute("""select * from student order by age desc""")
    # row = cursor.fetchone()
    # row = dict(row)
    # print(row["name"], row)

    """新增資料"""
    # try:
    #     # 新增1條資料
    #     # cursor.execute("""INSERT INTO student (name,age,sex,mobile,money) VALUES ('小明', 15, false,'17835492923',1300.00)""")
    #     # conn.commit()
    #     # conn.close()
    #
    #     data = [
    #         {"name": "小白", "age": 15, "sex": False, "mobile": "15912341234", "money": 880},
    #         {"name": "小黑", "age": 16, "sex": True,  "mobile": "15992929332", "money": 1220},
    #     ]
    #     cursor.executemany("""INSERT INTO student (name,age,sex,mobile,money) VALUES (%(name)s, %(age)s, %(sex)s, %(mobile)s,%(money)s)""", data)
    #     conn.commit()
    #     conn.close()
    #
    # except Exception as e:
    #     print(f"新增資料失敗:{e}")


    """更新/刪除資料"""
    # cursor.execute("""update student set money=money+1000 where name = '小明'""")
    # conn.commit()

Django連線postgresql

模組安裝:

pip install psycopg2-binary

settings.dev,程式碼:

DATABASES = {
 'default': {
     'ENGINE': 'django.db.backends.postgresql_psycopg2',
     'NAME': 'cps',
     'USER': 'cps_user',
     'PASSWORD': 'password',
     'HOST': '127.0.0.1',
     'PORT': '5432',
 }
}