Click here to view and discuss this page in DocCommentXchange. In the future, you will be sent there automatically.

SQL Anywhere 12.0.0 (中文) » SQL Anywhere 服务器 - 编程 » Perl DBI 支持 » 编写使用 DBD::SQLAnywhere 的 Perl 脚本

 

选择数据

获得了打开的连接的句柄后,您可以访问和修改存储在数据库中的数据。可能最简单的操作是检索某些行并输出它们。

必须先准备好返回行集的 SQL 语句,然后才能执行它们。prepare 方法为该语句返回一个句柄。使用该句柄执行语句,然后检索关于结果集和结果集的行的元信息。



#!/usr/local/bin/perl -w
#
use DBI;
use strict;
my $database = "demo";
my $data_src = "DBI:SQLAnywhere:SERVER=$database;DBN=$database";
my $uid      = "DBA";
my $pwd      = "sql";
my $sel_stmt = "SELECT ID, GivenName, Surname
                FROM Customers
                ORDER BY GivenName, Surname"; 
my %defaults = (
     AutoCommit => 0, # Require explicit commit or rollback.
     PrintError => 0
   );
my $dbh = DBI->connect($data_src, $uid, $pwd, \%defaults)
  or die "Cannot connect to $data_src: $DBI::errstr\n";
&db_query($sel_stmt, $dbh);
$dbh->rollback;
$dbh->disconnect;
exit(0);

sub db_query {
      my($sel, $dbh) = @_;
      my($row, $sth) = undef;
      $sth = $dbh->prepare($sel);
      $sth->execute;
      print "Fields:     $sth->{NUM_OF_FIELDS}\n";
      print "Params:     $sth->{NUM_OF_PARAMS}\n\n";
      print join("\t\t", @{$sth->{NAME}}), "\n\n";
      while($row = $sth->fetchrow_arrayref) {
         print join("\t\t", @$row), "\n";
      }
      $sth = undef;
}
__END__

直到 Perl 语句句柄被破坏,预准备语句才会从数据库服务器上删除。要破坏语句句柄,请重新使用变量或将其设置为 undef。调用 finish 方法不会删除句柄。实际不应调用 finish 方法,除非决定不完成读取结果集的操作。

要检测句柄泄漏,缺省情况下 SQL Anywhere 数据库服务器将允许的游标和准备好的语句数量限制为每个连接最多 50 个。如果超过这些限制,资源调控器自动生成错误。如果收到此错误,请检查未被释放的语句句柄。请谨慎使用 prepare_cached,因为语句句柄并没有被释放。

如有必要,可通过设置 max_cursor_count 和 max_statement_count 选项来修改这些限制。请参见max_cursor_count 选项max_statement_count 选项