我在perl中有此脚本,该程序解析一个日志文件并将结果发送到数据库中,我的难题是我的脚本仅插入一个请求,我需要插入多个请求:

#Connect to the database.
my $dbh = DBI->connect("DBI:mysql:database=database;host=IP",
"hostname", 'password',
{'RaiseError' => 1});



while (my ($user, $ref) = each %counts) {
  while (my ($program, $count) = each %$ref) {
    #print "$count OSUSER with session $user and with program $program\n";
    print "time = $time, count = $count, user = $user, program = $program, last_line = $last_line\n";

    $request ="'$time', '$count', '$user', '$program', $last_line";

    my $sth = $dbh->prepare("REPLACE `test` (time, nb, os_name, program, last_line) VALUES($request);")
    or die "prepare statement failed: $dbh->errstr()";

    $sth->execute() or die "execution failed: $dbh->errstr()";
    print $sth->rows . " rows found.\n";
    $sth->finish;
  }
}


我的日志:

       ID USER                    TERMINAL        SERVICE
---------- ------------------------- --------------- -------------------------
         1 toto                    titi     roro
         2 toto                    titi     roro
         4 gigi                    gege        fefe


我的数据库:

+----+---------------------+-----------+-------------+----------------+-----------+
| ID | time                | nb        | os_name     | program        | last_line |
+----+---------------------+-----------+-------------+----------------+-----------+
| 15  | 2019-01-04 14:00:00|        33 | titi        | roro           | 109       |


我想要 :

+----+---------------------+-----------+-------------+----------------+-----------+
| ID | time                | nb        | os_name     | program        | last_line |
+----+---------------------+-----------+-------------+----------------+-----------+
| 15  | 2019-01-04 14:00:00|        33 | titi        | roro           | 109       |
| 16  | 2019-01-04 14:00:00|        9  | gege        | fefe           | 109       |


(由Dave Cross添加-从注释复制。这是表定义。)

CREATE TABLE test (
  ID INT UNSIGNED NOT NULL AUTO_INCREMENT,
  time datetime NOT NULL,
  nb int NOT NULL,
  os_name nvarchar(100) NOT NULL,
  program nvarchar(100) NOT NULL,
  last_line nvarchar(100)NOT NULL,
  PRIMARY KEY (ID),
  UNIQUE KEY (time)
) ENGINE=InnoDB;

最佳答案

manual for REPLACE


  REPLACE的工作原理与INSERT完全相同,不同之处在于,如果表中的旧行与PRIMARY KEYUNIQUE索引的新行具有相同的值,则在插入新行之前删除该旧行。


(强调:我)

你有它。您有两次相同的2019-01-04 14:00:00时间。 REPLACE第二个时,第一个被删除

尝试删除time上的唯一索引。

关于mysql - perl-在数据库中发送多个请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54042288/

10-11 12:35