0

我有一个想法,我想制作一个可以进行选择查询的子程序,然后将结果复制到同一个表中,但有一些重要的更改。我的问题是,我在其中运行 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;
}
4

1 回答 1

3

该怎么办

你想要的是:

$fieldnames   = join ', ' => map { $dbh->quote_identifier($_) } keys %row;
$placeholders = join ', ' => map { '?' } values %row;
...
$sth = $dbh->prepare('INSERT INTO t ($fieldnames) VALUES ($placeholders)');
$sth->execute(values %row);

quote_identifier调用是为了安全起见,以防您的列名与关键字冲突或需要特殊编码或引用。)

为什么?

您的即时问题是您引用的值然后绑定到占位符(将值与引号绑定)并将字符串“null”绑定到占位符(绑定字符串“null”)。这会导致某些外键约束失败,因为您的 FKEY 可能不是文字字符串“null”,也不是表示带引号的数字的字符串(例如,它可能是数字 123 而不是嵌入引号“'123'”的字符串)。

作为参考,绑定字符串、包含引号的字符串、数字文字以及undef在 DBI 下通常是这样工作的:

 my $sth = $dbh->prepare('INSERT INTO t (a,b,c,d,e) VALUES (?,?,?,?,?)');
 $sth->execute("'quoted'", 'null', undef, 123, "a string");
 # Approximately the same as:
 #  INSERT INTO t (a,b,c,d,e) VALUES ('''quoted''', 'null', NULL, 123, 'a string');
 #                                        ^           ^      ^     ^     ^
 #               a string with quotes ----+           |      |     |     |
 #                                                    |      |     |     |
 #               a string (not the NULL value) -------+      |     |     |
 #                                                           |     |     |
 #               NULL (not the string 'null')----------------+     |     |
 #                                                                 |     |
 #               numeric literal ----------------------------------+     |
 #                                                                       |
 #               another string -----------------------------------------+
于 2013-11-01T15:36:30.317 回答