Truy cập cơ sở dữ liệu (CSDL) có tên openspace_db với username là toan
$ psql d openspace_db -U toan
Ở đây ngầm định host là local, nếu muốn truy cập PostgreSQL cài ở máy khác thì phải cung cấp thông tin host, chẳng hạn như sau :
$ psql d openspace_db -U toan -h <host name>
Sau khi truy cập ta có thể dùng meta-command \l để hiển thị các cơ sở dữ liệu (database) hiện có trong PostgreSQL
openspace_db=# \l
List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------------------+----------+----------+------------+------------+----------------------- openspace_db | toan | UTF8 | en_US.utf8 | en_US.utf8 |
Thoát khỏi hiển thị này bằng cách gõ lệnh \q
Tạo một cơ sở dữ liệu mới mang tên openspace_vn_db, nhớ đừng quyên dấu chấm phẩy (;) ở cuối, vì psql nhận biết kết thúc dòng lệnh bằng dấu này
openspace_db=# create database openspace_vn_db; CREATE DATABASE
Truy cập đến cơ sở dữ liệu mới tạo này bằng cách gõ lệnh \c như sau
openspace_db=# \c openspace_vn_db You are now connected to database "openspace_vn_db" as user "postgres". openspace_vn_db=#
Gõ lệnh \d để xem các quan hệ (relation : table, view, index, sequence, foreign talbe) của CSDL này
openspace_vn_db=# \d No relations found.
Tạo một bảng dữ liệu có tên là mobile
openspace_vn_db=# create table mobile(id int, name varchar); CREATE TABLE
Gõ lại lệnh \d, ta có
openspace_vn_db=# \d List of relations Schema | Name | Type | Owner --------+--------+-------+---------- public | mobile | table | toan (1 row)
Thêm dữ liệu vào bảng
openspace_vn_db=# insert into mobile values(0, 'Samsung Galaxy S4'); INSERT 0 1 openspace_vn_db=# insert into mobile values(1, 'iPhone 6'); INSERT 0 1
Xem dữ liệu trong bảng
openspace_vn_db=# select * from mobile; id | name ----+------------------- 0 | Samsung Galaxy S4 1 | iPhone 6 (2 rows)
Ta có thể nhập đọc dữ liệu vào (input) từ tập tin với lệnh \i, chẳng hạn tạo tập tin data.sql với nội dung sau :
create table provider(id int, name varchar, country varchar); insert into provider values(0, 'Samsung', 'Korea'); insert into provider values(1, 'Apple', 'United States');
Rồi gõ lệnh
openspace_vn_db=# \i data.sql CREATE TABLE INSERT 0 1 INSERT 0 1 openspace_vn_db=# \d List of relations Schema | Name | Type | Owner --------+----------+-------+---------- public | mobile | table | toan public | provider | table | toan (2 rows)
Ta có thể nhập nội dung vào PostgreSQL từ giao diện tương tác dòng lệnh của hệ điều hành (Ubuntu chẳng hạn). Trước hết ta xoá bảng dữ liệu provider vừa tạo và thoát khỏi psql với lệnh \q như sau
openspace_vn_db=# drop table provider; DROP TABLE openspace_vn_db=# \q
Rồi nhập dữ liệu vào từ tập tin như sau
$ psql -d openspace_vn_db -U toan -f data.sql CREATE TABLE INSERT 0 1 INSERT 0 1
Ta có thể tìm kiếm các quan hệ wildchar như sau (mo* : Các quan hệ có tên bắt đầu bằng mo)
openspace_vn_db=# \d mo* Table "public.mobile" Column | Type | Modifiers --------+-------------------+----------- id | integer | name | character varying |