0

我用 JSON API 中的数据散列填充了一个数组,我想将其加载到 SQLite 表中。生成此表的(复合)主键,以便以后的 JSON 拉取不会包含与旧主键关联的任何新信息,但 /will/ 包含具有新主键的新信息。(具体来说,它由日期和唯一标识我需要信息的每个对象的 ID 组合而成。)

与其笨拙地摆弄 API 参数,我宁愿让程序丢弃上面给出的表中已经存在的信息,但我无法正确跳过循环。

use DBI;
use 5.010;

#DLing information, processing, sanitising, etc. omitted

foreach my $hash (@{$data{$key}}) {
    my %data = %{$hash->{'row'}};
    my $date = $data{'date'};
    my $id = $data{'id'};
    my @pkey = [$date, $id]; #Generate a Perl array corresponding to the primary key, e.g. ['2013-09-10','0001']
    next if @pkey ~~ @allkeys; #Trying to use the 5.010 smart match operator to check if primary key already processed, and skip the entry if it is
    push(@allkeys,[@pkey]); 
    #Other stuff omitted--nothing to do with the pkey issue#
    my $sql = sprintf "INSERT INTO %s (date,id,low,high,avg) VALUES ('%s', %s, %s, %s, %s)",
        $table, $date, $id, $low, $high, $avg; #Values initialised earlier in script
    $dbh->do($sql);
}

这就是我目前正在尝试的,但它仍然在第一次操作时死亡;更简单的是让循环跳过特定错误类型“DBD::SQLite::db do failed: columns date, typeID are not unique”而不是死掉,但我还没有从哪里开始。

为了完整起见,数据库模式:

CREATE TABLE table (
            date TEXT,
            id INTEGER,
            low REAL,
            high REAL,
            avg REAL,
            PRIMARY KEY (date,id)
    );
4

1 回答 1

3

To not insert records that would violate a UNIQUE constraint, use INSERT OR IGNORE:

INSERT OR IGNORE INTO TheRealTableName(date,id,low,high,avg) VALUES (?,?,?,?,?)
于 2013-09-10T09:01:19.117 回答