1. 創建數據庫
法一:用登入默認用戶postgresql創建
注:創建語句結束要記得加;
- 用postgresql登入數據庫
sudo su - postgres
psql
- 創建用戶
CREATE USER dbuser WITH PASSWORD 'password';
- 創建庫
CREATE DATABASE exampledb OWNER dbuser;
- 授權
GRANT ALL PRIVILEGES ON DATABASE exampledb to dbuser;
- 退出
\q
法二:在shell
- 創建用戶
sudo -u postgres createuser --superuser dbuser
- 設置密碼
sudo -u postgres psql
\password dbuser
\q
- 創建庫
sudo -u postgres createdb -O dbuser exampledb
2. 登入數據庫
psql -U dbuser -d exampledb -h 127.0.0.1 -p 5432
上面命令的參數含義如下:-U指定用戶,-d指定數據庫,-h指定服務器,-p指定端口。
psql
用當前用戶登入當前庫
psql database_name
用當前用戶登入指定庫
另外,如果要恢復外部數據,可以使用下面的命令。
psql exampledb < exampledb.sql
導入外部數據
- 備份:
sudo -u postgres pg_dump database | gzip -9 > backup_name.psql.gz
- 恢復:
gunzip -c backup_name.psql.gz | psql db_name
常用命令
關閉服務
sudo pkill -u postgres #(kills all procs running as user postgres) or
pkill postgres #(kills all procs named 'postgres')
查看所有用戶
postgres=# \du
更改密碼
postgres=# \password dbuser
postgres=# \q
刪除用戶
postgres=# drop user dbuser;
查看所有數據庫
postgres=# \l
切換數據庫
postgres=# \c exampledb
查看表
postgres=# \d
查看表結構
postgres=# \d table_name
常用控制臺命令
\password
設置密碼。
\q
退出。
\h
查看SQL命令的解釋,比如\h select。
\?
查看psql命令列表。
\l
列出所有數據庫。
\c [database_name]
連接其他數據庫。
\d
列出當前數據庫的所有表格。
\d [table_name]
列出某一張表格的結構。
\du
列出所有用戶。
\e
打開文本編輯器。
q\conninfo
列出當前數據庫和連接的信息。