插入或忽略后受影响的行数

时间:2014-06-24 17:53:44

标签: perl sqlite dbi

perl代码给出了受影响的行数为1,即使在使用DBI模块插入sqlite数据库时由于PRIMARY KEY CONSTRAINT而导致sql语句忽略该记录。

my $stmt = 'INSERT OR IGNORE INTO table1 (ID, Name) VALUES (?,?)';
my $sth = $dbh->prepare($stmt);

$sth->bind_param( 1, $id, SQL_VARCHAR );
$sth->bind_param( 2, $name, SQL_VARCHAR );

my $row =  $sth->execute() or die $DBI::errstr;
print "Row affected for id[$id]- $row\n";

对于ID & NAME为复合主键的下面数据集,它总是给我$ row为1 -

ID   NAME
1    AAA
1    BBB
1    AAA
2    BBB
2    BBB

我在这里做错了什么。我需要根据值0f $ row执行另一段代码,在IGNORE的情况下为0,在INSERTION的情况下为1。

还有其他办法可以处理吗?

1 个答案:

答案 0 :(得分:0)

use strict;
use warnings;
use 5.016;
use DBI;

my $h = DBI->connect("dbi:SQLite:db=x.db");
eval {
    $h->do(q/drop table test/);
};

$h->do(q/create table test (id integer, name varchar(10), constraint xx unique(id,name))/);

my $s = $h->prepare(q/insert or ignore into test values(?,?)/);
my @values = ([1, 'AAA'], [1, 'BBB'], [1, 'AAA'], [2, 'BBB'], [2, 'BBB']);
foreach (@values) {
    my $affected = $s->execute(@{$_});
    say join(",", @{$_}) . " = $affected";
}
$h->disconnect;

输出

1,AAA = 1
1,BBB = 1
1,AAA = 0E0
2,BBB = 1
2,BBB = 0E0

对我来说看起来是正确的。我使用的是DBI 1.631和DBD :: SQLite 1.42。