繁体   English   中英

具有Perl DBI模块的关系表

[英]Relational table with perl dbi module

我想用这两个表之间的perl创建一个关系表,并在其中插入数据:

$create_query = qq{
    create table article(
        id_article int(10) auto_increment NOT NULL,
        url MEDIUMTEXT COLLATE utf8_general_ci,
        html_extr_text TEXT COLLATE utf8_general_ci,
        concord_file TEXT COLLATE utf8_general_ci,
        sys_time VARCHAR(50),
        primary key (id_article)
        )
};
$dbh->do($create_query);

 $create_query = qq{
     create table event(
         id_event int(10) auto_increment NOT NULL,
         event MEDIUMTEXT COLLATE utf8_general_ci,
         primary key (id_event)
         )
};
$dbh->do($create_query);

现在,关系表如下所示:

$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);

有人知道为了填充“ article_event_index”表应该使用perl语句吗? 对于其他表,我为每个表使用数组,如下所示:

my $i_event;
my $id_event = 0;
my @event_index;
for ($i_event = 0; $i_event < @event_prepare; $i_event++){
    $dbh->do("
        INSERT INTO `event`(`id_event`, `event`)
        VALUES ('$id_event', '$event_prepare[$i_event]')
        ") || die $dbh->errstr;
    push @event_index, $i_event;
}
$id_event++;

在这种情况下,'id_event'是通过$ id_event的增量生成的。 如果我想在索引表中重用此ID,这是一个好习惯吗?

除了Dave Sherohman的回复以外,以下是关于您的代码的一些注释:

您应该考虑为插入使用准备好的语句:

my $sth = $dbh->prepare("INSERT INTO `event`(`id_event`, `event`) VALUES (?,?)");

然后,在循环中,您只需为需要插入的每一行执行此操作:

$sth->execute($id_event, $event_prepare[$i_event]);

这更简单(它为您处理报价),更安全(防止SQL注入),并且速度更快。

另外,您不必仅通过数组就可以使用C风格的循环。 您可以使用以下形式之一:

for my $i_event (0..$#event_prepare){
    #if you need the array index.
}

for my $event (@event_prepare) {
    #if you don't need the array index.
}

另外,这只是一个首选项,但是我不喜欢{ ... }作为字符串定界符,因为它们看起来太像代码块。

由于id_event字段定义为auto_increment ,您可以让数据库为您生成id值,这是我通常这样做的方式,以避免出现竞争情况。 (即,如果两个单独的用户/进程尝试同时插入行并且都生成相同的id值,则提交第二个的用户/进程将失败。)

插入一行后,如果需要将其用作另一个表中的外键,则可以使用DBI的last_insert_id方法获取新行的自动生成的id值:

my $id = $dbh->last_insert_id(undef, undef, 'event', 'id_event');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM