我在 Perl 中使用DBI
模块和DBD:mysql
.
这个将字段url
, html_extr_text
, concord_file
, 和sys_time
插入到表中article
:
my @fields = (qw(url html_extr_text concord_file sys_time));
my $fieldlist = join ", ", @fields;
my $field_placeholders = join ", ", map {'?'} @fields;
my $insert_query = qq{
INSERT INTO article ($fieldlist)
VALUES ($field_placeholders)
};
my $sth = $dbh->prepare($insert_query);
my $id_article;
my @id_articles;
foreach my $article_index (0 .. @output_concord_files_prepare) {
$field_placeholders = $sth->execute(
$url_prepare[$article_index],
$html_pages_files_extended[$article_index],
$output_concord_files_prepare[$article_index],
$sys_time_prepare[$article_index]);
$id_article = $dbh->last_insert_id(undef, undef, 'article', 'id_article');
push @id_articles, $id_article;
if ($field_placeholders != 1) {
die "Error inserting records, only [$field_placeholders] got inserted: " . $sth->insert->errstr;
}
}
print "@id_articles\n";
而这个将字段event
插入表中event
:
@fields = (qw(event));
$fieldlist = join ", ", @fields;
$field_placeholders = join ", ", map {'?'} @fields;
$insert_query = qq{
INSERT INTO event ($fieldlist)
VALUES ($field_placeholders)
};
$sth = $dbh->prepare($insert_query);
my $id_event;
my @id_events;
foreach my $event_index (0 .. @event_prepare){
$field_placeholders = $sth->execute($event_prepare[$event_index]);
$id_event = $dbh->last_insert_id(undef, undef, 'event', 'id_event');
push @id_events, $id_event;
if ($field_placeholders != 1){
die "Error inserting records, only [$field_placeholders] got inserted: " . $sth->insert->errstr;
}
}
print "@id_events\n";
我想创建第三个一对多关系表。因为,一篇文章包含多个事件,所以我有这个文件:
output_concord/concord.0.txt -> earthquake
output_concord/concord.0.txt -> avalanche
output_concord/concord.0.txt -> snowfall
output_concord/concord.1.txt -> avalanche
output_concord/concord.1.txt -> rock fall
output_concord/concord.1.txt -> mud slide
output_concord/concord.4.txt -> avalanche
output_concord/concord.4.txt -> rochfall
output_concord/concord.4.txt -> topple
...
如您所见,我使用LAST_INSERT_ID
. 但是我真的不知道如何进行下一步。
使用此文件,我如何将前两个表的 ID 插入第三个表“article_event_index”。
它会是这样的:
$create_query = qq{
create table article_event_index(
id_article int(10) NOT NULL,
id_event int(10) NOT NULL,
primary key (id_article, id_event),
foreign key (id_article) references article (id_article),
foreign key (id_event) references event (id_event)
)
};
$dbh->do($create_query);
它将包含遵循模式的关系
1-1, 1-2, 1-3, 2-4, 3-5 ...
我是 Perl 和数据库的新手,所以很难制定我想要做什么。我希望我足够清楚。