【发布时间】:2019-05-31 05:21:17
【问题描述】:
我在 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;
【问题讨论】:
-
你为什么使用
REPLACE没有WHERE子句? -
另外,为什么不在循环前做好准备并在执行中使用占位符?
-
用替换我可以添加更多请求
-
使用占位符值。您不能只在查询中插入原始字符串。
-
VALUES($request)说你没有使用占位符。我可以在前面的行中看到您刚刚将数据拍入 没有转义 这是一个huge problem。