啟動數(shù)據(jù)庫
postgres -h hostname -p 5432
進入控制臺
sudo -u postgres psql
或
psql -U dbuser -d exampledb -h 127.0.0.1 -p 5432
退出
postgres=# \q
創(chuàng)建用戶
sudo -u postgres createuser dbuser
或
sudo -u postgres psql
postgres=# CREATE USER dbuser WITH PASSWORD 'password';
查看所有用戶
postgres=# \du
更改密碼
postgres=# \password dbuser
postgres=# \q
刪除用戶
postgres=# drop user dbuser;
創(chuàng)建數(shù)據(jù)庫
postgres=# CREATE DATABASE exampledb OWNER dbuser;
postgres=# GRANT ALL PRIVILEGES ON DATABASE exampledb to dbuser;
postgres=# \c exampledb;
postgres=# ALTER SCHEMA public OWNER to dbuser;
postgres=# GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public TO dbuser;
postgres=# GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public TO dbuser;
或
sudo -u postgres createdb -O dbuser exampledb
查看所有數(shù)據(jù)庫
postgres=# \l
切換數(shù)據(jù)庫
postgres=# \c exampledb
查看表
postgres=# \d
查看表結(jié)構(gòu)
postgres=# \d user_tab1
常用控制臺命令
\password 設(shè)置密碼。
\q 退出。
\h 查看SQL命令的解釋,比如\h select。
? 查看psql命令列表。
\l 列出所有數(shù)據(jù)庫。
\c [database_name] 連接其他數(shù)據(jù)庫。
\d 列出當(dāng)前數(shù)據(jù)庫的所有表格。
\d [table_name] 列出某一張表格的結(jié)構(gòu)。
\du 列出所有用戶。
\e 打開文本編輯器。
\conninfo 列出當(dāng)前數(shù)據(jù)庫和連接的信息。
基本的 SQL 語句
創(chuàng)建新表
CREATE TABLE user_tbl(name VARCHAR(20), signup_date DATE);
插入數(shù)據(jù)
INSERT INTO user_tbl(name, signup_date) VALUES('張三', '2013-12-22');
查詢記錄
SELECT * FROM user_tbl;
更新數(shù)據(jù)
UPDATE user_tbl set name = '李四' WHERE name = '張三';
刪除記錄
DELETE FROM user_tbl WHERE name = '李四' ;
添加字段
ALTER TABLE user_tbl ADD email VARCHAR(40);
更改字段類型
ALTER TABLE user_tbl ALTER COLUMN signup_date SET NOT NULL;
設(shè)置字段默認值(注意字符串使用單引號)
ALTER TABLE user_tbl ALTER COLUMN email SET DEFAULT 'example@example.com';
去除字段默認值
ALTER TABLE user_tbl ALTER email DROP DEFAULT;
重命名字段
ALTER TABLE user_tbl RENAME COLUMN signup_date TO signup;
刪除字段
ALTER TABLE user_tbl DROP COLUMN email;
表重命名
ALTER TABLE user_tbl RENAME TO backup_tbl;
刪除表
DROP TABLE IF EXISTS backup_tbl;
刪除庫
\c hello2;
DROP DATABASE IF EXISTS hello;
從上面的命令可以看出基本的 SQL 語句跟 MySQL 是一樣的。
備份、恢復(fù)
pg_dump 備份
pg_dumpall 備份所有數(shù)據(jù)庫
pg_restore 恢復(fù)
psql exampledb < exampledb.sql 導(dǎo)入數(shù)據(jù)
example:
pg_dump --format=t -d db_name -U user_name -W -h 127.0.0.1 > dump.sql
pg_restore -d db_name -h 127.0.0.1 -U user_name < dump.sql