创建数据库和表#

本节通过使用 OushuDB 的命令行工具 psql 来说明如何创建基本数据库对象:database 和 table 。因为 OushuDB 和 PostgreSQL 兼容,所以使用 OushuDB 的方式和使用 PostgresSQL 的方式基本相同,如果 OushuDB 的文档有些地方说明不清楚的话,用户也可以通过查阅 PostgresSQL 的帮助文档来了解更多关于 OushuDB 的信息。

下面这条命令使用 psql 连接 OushuDB 缺省安装的数据库 postgres,然后创建一个新的数据库 test,并在新的数据库中创建一个表 foo。

 1 $ psql -d postgres
 2 psql (8.2.15)
 3 Type "help" for help.
 4
 5 postgres=# create database test;  # 创建数据库 test
 6 CREATE DATABASE
 7
 8 postgres=# \c test  # 连接进入 test 数据库
 9 You are now connected to database "test" as user "oushu".
10
11 test=# create table foo(id int, name varchar);  # 创建表 foo
12 CREATE TABLE
13
14 test=# \d  # 显示当前数据库 test 中所有表
15            List of relations
16 Schema | Name | Type  |  Owner   |   Storage
17--------+------+-------+----------+-------------
18 public | foo  | table | oushu | append only
19 (1 row)
20
21
22 test=# insert into foo values(1, 'hawq'),(2, 'hdfs');
23 INSERT 0 2
24
25 test=# select * from foo; # 从表 foo 中选择数据
26  id | name
27 ----+------
28   1 | hawq
29   2 | hdfs
30 (2 rows)
31
32 如果想删除表或者数据库的话可以使用 drop 语句。
33
34 test=# drop table foo;
35 DROP TABLE
36
37 test=# \d
38 No relations found.
39
40 test=# drop database test;  # 因为现在在 test 数据库中,所以不能删除
41 ERROR:  cannot drop the currently open database
42
43 test=# \c postgres  # 首先连接到 postgres 数据库,然后删除 test 数据库
44 You are now connected to database "postgres" as user "oushu".
45
46 postgres=# drop database test;
47 DROP DATABASE