2

我是 perl 脚本的新手,我在尝试执行两个 sql 时发现了一个问题,这里有代码,肯定不是最好的。

use DBI;
use DBD::mysql;
use Socket;
use strict;
use warnings;

# CONFIG VARIABLES
my $platform = 'mysql';
my $database = 'database_name';
my $host = 'hostname';
my $port = '3306';
my $user ='user';
my $pw ='password';

# DATA SOURCE NAME
my $dsn = "dbi:mysql:$database:$host:3306";

# PERL DBI CONNECT
my $dbh = DBI->connect($dsn,$user,$pw,{RaiseError=>1,PrintError=>1}) or die "Could not connect to database: $DBI::errstr";

# READ THE LASTID OF THE DATABASE
my $queryID = "SELECT event.id from snorby.event order by event.id desc limit 1";
my $lastid = $dbh->selectrow_array($queryID);

#HIGH
while ( 1 == 1 )
{
my $query = "SELECT event.id, inet_ntoa(iphdr.ip_src) as 'src', tcp_sport, inet_ntoa(iphdr.ip_dst) as 'dst', tcp_dport, signature.sig_name, event.timestamp, unhex(data.data_payload) from snorby.event join snorby.signature on signature.sig_id = event.signature join snorby.iphdr on event.cid=iphdr.cid and event.sid=iphdr.sid join snorby.data on event.cid=data.cid and event.sid=data.sid join snorby.tcphdr on event.cid=tcphdr.cid and event.sid=tcphdr.sid where event.id > $lastid and signature.sig_priority = '1' order by event.id";

my $sth = $dbh->prepare($query);
$sth->execute() or die "SQL Error: $DBI::errstr\n";

# BIND TABLE COLUMNS TO VARIABLES
my($eventid,$src,$sport,$dst,$dport,$signature,$timestamp,$payload);
$sth->bind_columns(undef, \$eventid, \$src, \$sport, \$dst, \$dport, \$signature, \$timestamp, \$payload);

# LOOP THROUGH RESULTS  
while($sth->fetch) {

my $src_temp = inet_aton($src);
my $dst_temp = inet_aton($dst);

print "IT WORKS!";

}

所以,如果我评论这部分代码

# READ THE LASTID OF THE DATABASE
my $queryID = "SELECT event.id from snorby.event order by event.id desc limit 1";
my $lastid = $dbh->selectrow_array($queryID);

一切正常,但是当我尝试先执行这个时,脚本在这一行停止响应:

while($sth->fetch) {

我试图调试代码,寻找教程,阅读了很多页面,但无法弄清楚问题出在哪里:(

问候。

** * *更新* ** * ****

我想我在经过更多调试后发现了问题,但没有找到解决方案。在名为 $query 的第二个 sql 上,我传递了在第一个 sql 上获得的变量 $lastid,请参阅:

my $query = "SELECT stuff from table join things where event.id > **$lastid** and blablabla

例如,如果我将 $lastid 更改为 13330506,则一切正常,因此似乎存在有关如何传递此变量的问题。奇怪的是,当我在 $lastid 的内容中打印 $lastid 的 $query 是正确的时,数字出现了......奇怪,至少对我来说。

4

1 回答 1

1

如果您阅读文档http://search.cpan.org/dist/DBI/DBI.pm 您会看到没有 ->fetch 功能,但是有各种 fetch 方法:

@row_ary  = $sth->fetchrow_array;
$ary_ref  = $sth->fetchrow_arrayref;
$hash_ref = $sth->fetchrow_hashref;

$ary_ref  = $sth->fetchall_arrayref;
$ary_ref  = $sth->fetchall_arrayref( $slice, $max_rows );

$hash_ref = $sth->fetchall_hashref( $key_field );

每个都返回一个引用,您应该将其存储在变量中以供以后使用,例如:

while ( @row = $sth->fetchrow_array ) { ... }
while (my $data = $sth->fetchrow_hashref) { ... }

然后,您可以在循环中使用 @row 或 $data 来检索您需要的数据。

于 2013-09-25T07:26:12.393 回答