我有一个想法,我想制作一个可以进行选择查询的子程序,然后将结果复制到同一个表中,但有一些重要的更改。我的问题是,我在其中运行 sub 的某些表具有包含许多不同字符的大文本字段,其中一些会破坏我的插入语句。然后我将插入更改为使用参数绑定,但是当我这样做时,我的查询将不会运行,因为我的“配置文件”字段上有一些外键约束:
DBD::mysql::st execute failed: Cannot add or update a child row: a foreign key constraint fails (
retriever
.result
, CONSTRAINT result_ibfk_2
FOREIGN KEY (profile
) REFERENCES profile
(id
) ON DELETE CASCADE ON UPDATE CASCADE) at ./create_query.pl line 62.
Cannot add or update a child row: a foreign key constraint fails (retriever
.result
, CONSTRAINT result_ibfk_2
FOREIGN KEY (profile
) REFERENCES profile
(id
) ON DELETE CASCADE ON UPDATE CASCADE)
关于表的一些信息:
CREATE TABLE `result` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`profile` mediumint(8) unsigned NOT NULL DEFAULT '0',
CONSTRAINT `result_ibfk_2` FOREIGN KEY (`profile`) REFERENCES `profile` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
) ENGINE=InnoDB AUTO_INCREMENT=1037028383 DEFAULT CHARSET=utf8
这是我的代码:
#Define which rows to change
my $rows_to_change = {
'profile' => 621420,
};
#Define a select query, the results will then be copyed over
my $sql = "select * from result where profile = 639253";
#Define which table to work with
my $table = "result";
my @inserted_ids = create_insert_query($sql, $table, $rows_to_change);
for my $id (@inserted_ids){
print $id."\n";
}
$dbh->rollback();
$dbh->disconnect();
sub create_insert_query{
my $select = shift;
my $table = shift;
my $rows_to_change = shift;
my $result = $dbh->prepare($select);
$result->execute() or die $dbh->errstr;
my @inserted_ids;
while(my $row = $result->fetchrow_hashref){
delete $row->{'id'};
foreach my $key (keys %{$rows_to_change}){
$row->{$key} = $rows_to_change->{$key};
}
my @fields;
my @values;
for my $key (keys %{$row}){
push(@fields, $key);
if(defined $row->{$key}){
push(@values, "'$row->{$key}'");
}else{
push(@values, "null");
}
}
my $fields_string = join(", ", @fields);
my $values_string = join(", ", @values);
my $questionmarks = join( ',', map { '?' } @values );
my $query = qq[insert into $table ($fields_string) values ($questionmarks)];
my $sth = $dbh->prepare($query);
$sth->execute(@values) or die $dbh->errstr;
push(@inserted_ids, $sth->{mysql_insertid});
}
return @inserted_ids;
}