学习Perl DBI -- 处理查询语句

    在建立连接后, 就可以进行查询了. 可以用prepare函数来准备一个SQL语句, 获得一个Cursor的句柄(Handle)后就可以执行了, 如下所示:

my $sth = $dbh->prepare("select .....");

if (!defined($sth))
{
......
}

if ($sth->execute())
{
......
}

    在调用execute函数(如果成功返回True, 否则False)后, 接下来需要进行Fetch操作才能将查询的结果取出来, 取出记录有很多种方法:

my ($col1, $col2, ....);
while ( ($col1, $col2, ...) = $sth->fetchrow_array() )
{
.....
}

my @row;
while ( @row = $sth->fetchrow_array())
{
    print($row[0].",".$row[1].....);
}

my $rowref;
while ( $rowref = $sth->fetchrow_arrayref())
{
   print($rowref->[0].",".$rowref->[1].....);
}

my $rowref;
while ( $rowref = $sth->fetchrow_hashref())
{
   print($rowref->{col1}.",".$rowref->{col2}.....);
}

    在取完所有的记录后或你想要的记录后, 你可以调用一下finish方法:

$sth->finish();

    在这个例子中, 我们取记录都是一条一条地取的, 为了速度我们应当一批一批地读取记录, 这一点会在以后讲.

发表留言:

« Previous | Main | Next »

英语900句 | English 900

  • Yes, a lot of friends.
  • 是的, 很多.
  • You must have enjoyed yourself.
  • 你一定玩的很开心.
  • Yes, and I took many pictures.
  • 是的, 我还照了好多照片.
  • Please let me see them.
  • 让我看看.
  • Will you go shopping with me?
  • 你跟我去买东西吗?