[英]Using DBI in Perl to update multiple fields in one line?
I'm mediocre with perl and new to SQL, so excuse any lameness. 我是perl的平庸和SQL的新手,所以原谅任何跛脚。
I've got a perl script I'm working on that interacts with a database to keep track of users on IRC. 我有一个我正在研究的perl脚本,它与数据库交互以跟踪IRC上的用户。 From tutorials I've found, I've been able to create the db, create a table within, INSERT a new record, UPDATE a field in that record, and SELECT/find records based on a field.
从我发现的教程中,我已经能够创建数据库,在其中创建表,插入新记录,在该记录中更新字段,以及根据字段选择/查找记录。
The problem is, I can only figure out how to UPDATE one field at a time and that seems inefficient. 问题是,我只能弄清楚如何一次更新一个字段,这似乎效率低下。
The code to create the table: 创建表的代码:
my $sql = <<'END_SQL';
CREATE TABLE seenDB (
id INTEGER PRIMARY KEY,
date VARCHAR(10),
time VARCHAR(8),
nick VARCHAR(30) UNIQUE NOT NULL,
rawnick VARCHAR(100),
channel VARCHAR(32),
action VARCHAR(20),
message VARCHAR(380)
)
END_SQL
$dbh->do($sql);
And to insert a record using values I've determined elsewhere: 并使用我在其他地方确定的值插入记录:
$dbh->do('INSERT INTO seenDB (nick, rawnick, channel, action, message, date, time) VALUES (?, ?, ?, ?, ?, ?, ?)', undef, $nickString, $rawnickString, $channelString, $actionString, $messageString, $dateString, $timeString);
So, when the script needs to update, I'd like to update all of these fiends at once, but right now the only thing that works is one at a time, using syntax I got from the tutorial: 因此,当脚本需要更新时,我想立即更新所有这些恶魔,但是现在唯一可行的是一次一个,使用我从教程中获得的语法:
$dbh->do('UPDATE seenDB SET time = ? WHERE nick = ?',
undef,
$timeString,
$nickString);
I've tried the following syntaxes for multiple fields, but they fail: 我已经尝试了多个字段的以下语法,但它们失败了:
$dbh->do('UPDATE seenDB (rawnick, channel, action, message, date, time) VALUES (?, ?, ?, ?, ?, ?)', undef, $rawnickString, $channelString, $actionString, $messageString, $dateString, $timeString);
and 和
$dbh->do('UPDATE seenDB SET rawnick=$rawnickString channel=$channelString action=$actionString message=$messageString date=$dateString time=$timeString WHERE nick=$nickString');
Is there a better way to do this? 有一个更好的方法吗?
You can update several fields at once in pretty much the same way as you update a single field, just list them comma separated in the update, something like; 您可以使用与更新单个字段几乎相同的方式一次更新多个字段,只需在更新中列出逗号分隔,例如;
$dbh->do('UPDATE seenDB SET rawnick=?, channel=?, action=?, message=?, date=?, time=? WHERE nick=?',
undef,
$rawnickString,
$channelString,
$actionString,
$messageString,
$dateString,
$timeString,
$nickString
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.