PostgreSQL筆記及設定 — PSQL指令整理(以Ruby on Rails為例)
4 min readMay 16, 2019
Psql簡單介紹:
PostgreSQL是一個關聯式的資料庫,個人認為比MySQL/MariaDB強大的原因是,因為PostgreSQL可以支援一些不一樣的欄位型別,像是JSON type等等。這是有別於一般的SQL資料庫,同時這也是它的優勢跟特性。
##指令提示man createuser
##查看版本postgres —-version
Mac-osx上安裝psql:brew updatebrew install postgresqlinitdb /usr/local/var/postgrespg_ctl -D /usr/local/var/postgres startpg_ctl -D /usr/local/var/postgres stopurl:/usr/local/var/postgres
##MAC-osx卸載psqlbrew uninstall postgresqlbrew uninstall --ignore-dependencies postgresql
##Ubuntu上安裝Postgresql(ubuntu 16.04 OR 18.04)apt-get updateapt-get install postgresql postgresql-contrib
##進入psqlsudo su - postgrespsqlsudo vim /etc/postgresql/9.5/main/pg_hba.conf
#RubyonRails御用*(沒裝會撞牆)sudo apt-get install libpq-dev
##以使用者登入psqlpsql -h localhost -U you database_name
##列出所有使用者SELECT * FROM "pg_user”;
##當前使用者SELECT current_user;
##設定資料庫createdb test_db
##設定使用者*createuser -P {username}{password}
##設定使用者及資料庫*createdb -Otest -Eutf8 {database_name}psql {database}
##賦予權限*GRANT ALL PRIVILEGES ON DATABASE databasename TO username;
##重設密碼*ALTER USER user_name with password 'new_password’;
##刪除使用者删除user: revoke all on database databasename from username;(收回此需删除的用户对数据库的所有权限) (注:当前数据库有默认schema:public,试试这个) DROP user username;(现在删除就不会有任何权限受限而删除失败) GRANT ALL PRIVILEGES ON DATABASE databasename TO username;psql -U {username} {database} -h localhost -Wpsql -U p_andy test_db -h localhost -W#進入命令模式指令集#看有哪些資料庫\l#連線到資料庫\c#看有哪些表格\dt#查看有哪些欄位\d+#退出\q#使用者設定
#建立 使用者 -> 資料庫create database xxxdv owner user;
#設定使用者密碼:ALTER USER postgres WITH PASSWORD 'postgres';#登入方式sudo -u postgres psql (或xx_db)#使用 新的使用者 進行登入 psqlpsql -U test test_db -h localhost -W#查看執行過的資料庫遷移select * from schema_migrations;rails db補充: rails db:resethttp://etrex.blogspot.com/2017/03/postgresql-cli.html##Rails資料庫遷移指令集rails db:createrails db:droprails db:schema:loadrails db:schema:dumprails db:seedrails db:resetrails db:migrate:status