====== 另一个数据库插入例子museums-insert.pl ======
这是另一个向Oracle数据库插入数据的例子,与[[.:institutions-insert|institutions-insert.pl]]相同的部分不再描述。
===== 表结构 =====
除了表Institutions,另一张表是:
CREATE TABLE Museums
(
museum_id VARCHAR2(128 CHAR) NOT NULL,
name_cn VARCHAR2(128 CHAR) NOT NULL,
name_en VARCHAR2(512 BYTE),
address_cn VARCHAR2(256 CHAR),
address_en VARCHAR2(1024 BYTE),
website_cn VARCHAR2(128 CHAR),
website_en VARCHAR2(512 BYTE),
desc_cn VARCHAR2(1000 CHAR),
desc_en VARCHAR2(4000 BYTE),
institution_id NUMBER(10) NOT NULL
);
ALTER TABLE Museums ADD CONSTRAINT Museums_primary_key
PRIMARY KEY(museum_id);
ALTER TABLE Museums ADD CONSTRAINT MuInsId_must_in_ins
FOREIGN KEY(institution_id) REFERENCES Institutions(institution_id);
===== 代码简述 =====
表Museums与Institutions有外键约束。在插入Museums之前,需要先查询Institutions,结果放在哈希变量里:
my $sth = $dbh->prepare( q{
SELECT institution_id, name_cn FROM Institutions
}) or die "Can't prepare statement: $DBI::errstr";
my $rc = $sth->execute
or die "Can't execute statement: $DBI::errstr";
my %ins_ids;
while (my ($id, $name) = $sth->fetchrow_array) {
$ins_ids{$name} = $id;
}
后续就是同样的插入操作了,只是部分数据来自之前的查询结果:
if (!$flag) {
$sth->execute($museum_id, $name_cn, $name_en, $website_cn,
$website_en, $ins_ids{$ins_name});
}
完毕。
{{tag>Perl}}