三、创建示例表
下面,我们通过一个具体的在线交易应用为例来阐述上面介绍的事务概念。为此,我们需要先给这个示例程序在名为company的数据库中创建两个表:participant和trunk。同时,我们还会介绍各个表的用途和结构。建好表后,我们还需为它们填入一些样本数据,具体如下所示。
我们首先创建Participant表,这个表用来存放参与物品交换者的信息,包括他们的姓名、电子邮件地址和可用现金:
1 CREATE TABLE participant (
2 participantid SERIAL,
3 name TEXT NOT NULL,
4 email TEXT NOT NULL,
5 cash NUMERIC(5,2) NOT NULL,
6 PRIMARY KEY (participantid)
7 );
8 CREATE TABLE participant (
9 participantid SERIAL,
10 name TEXT NOT NULL,
11 email TEXT NOT NULL,
12 cash NUMERIC(5,2) NOT NULL,
13 PRIMARY KEY (participantid)
14 );
2 participantid SERIAL,
3 name TEXT NOT NULL,
4 email TEXT NOT NULL,
5 cash NUMERIC(5,2) NOT NULL,
6 PRIMARY KEY (participantid)
7 );
8 CREATE TABLE participant (
9 participantid SERIAL,
10 name TEXT NOT NULL,
11 email TEXT NOT NULL,
12 cash NUMERIC(5,2) NOT NULL,
13 PRIMARY KEY (participantid)
14 );
然后,我们开始创建trunk 表。这个表存储参与者所有的物品的有关信息,包括属主、名称、描述和价格:
1 CREATE TABLE trunk (
2 trunkid SERIAL,
3 participantid INTEGER NOT NULL REFERENCES participant(participantid),
4 name TEXT NOT NULL,
5 price NUMERIC(5,2) NOT NULL,
6 description TEXT NOT NULL,
7 PRIMARY KEY (trunkid)
8 );
2 trunkid SERIAL,
3 participantid INTEGER NOT NULL REFERENCES participant(participantid),
4 name TEXT NOT NULL,
5 price NUMERIC(5,2) NOT NULL,
6 description TEXT NOT NULL,
7 PRIMARY KEY (trunkid)
8 );
用到的表都建好了,下面我们开始添加样本数据。为简单起见,我们这里只添加了两名参与者,即Tom和Jack;并为trunks表添加了少量的物品,如下所示:
1 INSERT INTO participant (name,email,cash) VALUES
2 ('Tom','Tom@example.com','1100.00');
3 INSERT INTO participant (name,email,cash) VALUES
4 ('Jack','Jack@example.com','1150.00');
5 INSERT INTO trunk (participantid,name,price,description) VALUES
6 (1,'Linux CD','1.00','Complete OS on a CD'); INSERT INTO trunk (participantid,
7 name,price,description) VALUES
8 (2,'ComputerABC','12.99','a book about computer!');
9 INSERT INTO trunk (participantid,name,price,description) VALUES
10 (2,'Magazines','6.00','Stack of Computer Magazines');
2 ('Tom','Tom@example.com','1100.00');
3 INSERT INTO participant (name,email,cash) VALUES
4 ('Jack','Jack@example.com','1150.00');
5 INSERT INTO trunk (participantid,name,price,description) VALUES
6 (1,'Linux CD','1.00','Complete OS on a CD'); INSERT INTO trunk (participantid,
7 name,price,description) VALUES
8 (2,'ComputerABC','12.99','a book about computer!');
9 INSERT INTO trunk (participantid,name,price,description) VALUES
10 (2,'Magazines','6.00','Stack of Computer Magazines');