[英]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.