2.4 KiB
layout | status | published | title | author | date | categories | tags |
---|---|---|---|---|---|---|---|
post | publish | true | PostgreSQL 101 | [{display_name sipp11}] | 2013-10-26 | [database] | postgresql 101 |
I found that PostgreSQL works differently to MySQL. PostgreSQL will accept command from both command shell ($) and PostgreSQL shell (postgres=#). When you create database, drop database, you can do from command shell:
$ createdb <database-name> -E UTF8
$ dropdb <database-name>
while charset support listed here. or you can create database inside postgres shell.
$ psql
postgres=# create database <database-name>
postgres=# drop database <database-name>
To do some basic query, it's pretty like MySQL. However, it's vastly different when it comes to list/describe
postgres=# \l # show databases
postgres=# \connect <database-name> # use database
<database-name>=# \d # show tables
<database-name>=# \d <table-name> # show columns
<database-name>=# \d+ <table-name> # describe table
Configure for remote connection
Server side
Edit /etc/postgres/x.x/main/postgresql.conf
listen_addresses = '*'
Add line to /etc/postgres/x.x/main/pg_hba.conf
host all all 0.0.0.0/0 md5
or you could do things like 192.168.1.1/24
if you want to limit to your subnet.
Creating remote user isn't anything different from what local user is:
$ psql template1
template1=# create user <user-name> with password '<your-password>';
template1=# \connect <database-name>;
<database-name>=> GRANT USAGE ON SCHEMA public to <user-name>;
<database-name>=> GRANT SELECT ON ALL TABLES IN SCHEMA public TO <user-name>;
<database-name>=> GRANT UPDATE ON ALL TABLES IN SCHEMA public TO <user-name>;
<database-name>=> GRANT ALL ON ALL TABLES IN SCHEMA public TO <user-name>;
<database-name>=> ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO <user-name>;
<database-name>=> GRANT USAGE, SELECT ON SEQUENCE <table_name>_id_seq TO <user-name>;
<database-name>=> GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA <schema_name> TO <user-name>;
<database-name>=> \q
Client side
Pretty much like MySQL
$ psql -h <postgres-server> -d <database-name> -U <user-name>
If you don't have postgresql client yet
# apt-get install postgresql-client-x.x
while x.x means version, e.g. postgresql-client-9.1