log in
$ Psql (connect to the database, the default user and the database is postgres) $ psql -U <user> -d <dbname>
Database operations
// enumerate databases, equivalent to show databases
$ \l
// switch databases, comparable to use dbname
$ \c <dbname>
// list table, fairly and show tables
$ \dt
// View table structure, equivalent to desc
$ \d tblname
// Create a database
$ create database <dbname>
// delete the database
$ drop database <dbname>
// Create a table
$ Create table ([Field Name 1] [Type 1];, [2 Field Name] [Type 2], ...... <, primary key (field name m, field name n, ...)>; );
// insert data in the table
$ Insert into table ([m field name], [field name n], ......) values ([column values of m], [n the value of the column], ......);
// backup database
$ Pg_dump -U postgres -f /tmp/postgres.sql postgres (Export postgres database is saved as postgres.sql) $ Pg_dump -U postgres -f /tmp/postgres.sql -t test01 postgres (postgres database tables to export data of test01) $ Pg_dump -U postgres -F t -f /tmp/postgres.tar postgres (postgres database to export in the form of compressed tar saved as postgres.tar)
// restore the database
$ Psql -U postgres -f /tmp/postgres.sql bk01 (postgres.sql restore data to bk01 database) $ Pg_restore -U postgres -d bk01 /tmp/postgres.tar (postgres.tar restore data to bk01 database)
User Action
// Switch User
$ \c - <username>
// Create user and password
$ CREATE USER 'username' WITH PASSWORD 'password'; $ CREATE ROLE 'username' CREATEDB PASSWORD 'password' LOGIN; (create roles and grant to create the database login and password attributes)
// change the user password
$ ALTER USER 'username' WITH PASSWORD 'password';
// database authorization
$ GRANT ALL PRIVILEGES ON DATABASE 'dbname' TO 'username';
// modify user permissions
$ ALTER ROLE 'username' createdb; (grant create database permissions) $ ALTER ROLE 'username' superuser; (grant super administrator privileges)
// Role Properties
login | login only role with the LOGIN attribute can be used as the initial role name for the database connection. |
superuser | Database superuser |
createdb | Create a database permissions |
createrole | Allowing it to create or delete other common user roles (except for super user) |
replication | A user attribute do stream replication when used, generally set separately. |
password | Only works when asked to specify a password when you log in, such as md5 or password mode, connected with the authentication client related |
inherit | User group inherits a sign of the crew members can inherit the characteristics of the user group permissions |