我在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;
最佳答案
您的表定义(来自评论)包括:
UNIQUE KEY (time)
因此,对于任何时间
值,您的表格只能包含一行。
此外,您还可以在 SQL 中使用 REPLACE
。因此,当您第二次运行语句时,数据库会发现存在具有相同唯一键的现有行,因此它会更新该行而不是插入新行。
在我看来,您的代码完全按照预期工作。如果要添加更多行,则需要更改$time
中的值。
更新:
来自您对另一个答案的评论。
i tested with INSERT but don't work : DBD::mysql::st execute failed: Duplicate entry '2019-01-04 17:45:00' for key 'time'
是的!这正是应该发生的事情。通过将 time
列声明为 UNIQUE
,您就告诉数据库每个时间值只能在表中出现一次。因此,如果您尝试在同一时间插入另一行(这就是您正在做的事情),您会收到该错误。
因此,您从 INSERT
切换到 REPLACE
并且不会出现错误,但只插入一行 - 因为这就是 REPLACE
的作用。
您在表中给出的示例在时间列中有两个相同的值。当您对该列有 UNIQUE
定义时,这种情况就不会发生。这正是 UNIQUE
键要防止的事情。
您需要退后一步,仔细考虑一下您想要在表格中显示的内容。如果您希望表中出现重复的时间值,则需要删除表上的 UNIQUE
键定义(然后将 REPLACE
更改为 INSERT
) .
关于mysql - perl - 在数据库中发送多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54042288/