【问题标题】:Why doesn't my Perl DBI query return any results in a CGI script?为什么我的 Perl DBI 查询没有在 CGI 脚本中返回任何结果?
【发布时间】:2010-02-15 04:41:46
【问题描述】:

我是第一次使用 DBI(并且没有多久开始使用 Perl [2 周]),我似乎无法从数据库中获得任何结果。这是我所拥有的:

if( defined( $get{findAllPages} ) && defined( $post{ki} ) ){

   my ($database, $hostname, $port, $password, $user );

   $database = "#########";
   $hostname = "localhost";
   $password = "#########";
   $user = "###########";
   my $KI = $post{ki};

   # connect to the database
   my $dsn = "DBI:mysql:database=$database;host=$hostname;";
   my $dbh = DBI->connect($dsn, $user, $password);
   my $sth = $dbh->prepare("SELECT * FROM accounts WHERE KI = '" . $dbh->quote($KI) . "' ") or die "Could not select from table";
   $sth->execute();
   if( $sth->rows != 0 ) {
      my $ref = $sth->fetchrow_hashref();
      my $domain = $ref->{website};
      my $DB_username = $ref->{db_name};
      my $DB_password = $ref->{db_pass};
      $sth->finish();
      $dbh->disconnect();

      print "domian: " . $domain . "<br />\n";

      chomp(my $url = trim($domain));

就目前而言,它会检查KI 是否正确,然后检查行数是否有效。我无法工作的一点是从数组中返回值;

my $ref = $sth->fetchrow_hashref();
my $domain = $ref->{website};
my $DB_username = $ref->{db_name};
my $DB_password = $ref->{db_pass};

如果有人能告诉我哪里出错了,将不胜感激。

【问题讨论】:

    标签: mysql perl dbi


    【解决方案1】:

    尝试使用DBI 的错误处理来查看问题所在。参考Programming the Perl DBI, chapter 4(错误处理)或"DBI::mysql error handling" on Perlmonks

    【讨论】:

    • 谢谢,你能告诉我“or die”是否适用于在线 cgi 文件,因为我似乎永远无法将它输出到浏览器。
    • fetch() without execute().. 所以我猜...我的 $dsn = "DBI:mysql:database=$database;host=$hostname;";我的 $dbh = DBI->connect($dsn, $user, $password); my $sth = $dbh->prepare("SELECT * FROM accounts WHERE KI = '" . $dbh->quote($KI) . "' ") or die "Could not select from table"; $sth->执行(); if( $sth->rows != 0 ) { 我的 $ref = $sth->fetchrow_hashref(); $ref->执行();打印 $DBI::errstr;我的 $domain = $ref->{网站};我的 $DB_username = $ref->{db_name};我的 $DB_password = $ref->{db_pass}; $sth->finish(); $dbh->断开连接();应该这样做
    • 如果您使用 cgi,一种方法是使用 CGI::Carp。见perldoc.perl.org/CGI/…。顺便说一句,将代码发布在您的问题中,而不是在 cmets 中,因为格式不好。
    • grrr ... 当我在本地机器上从 cmd 运行时它工作正常,但是当我通过浏览器使用时告诉我做一件事,然后当我回到本地机器时,我所做的更改导致错误...
    • 浏览器告诉你做什么?
    【解决方案2】:

    当我看不到正在发生的事情时我经常做的事情:

    使用 Data::Dumper;

    我的 $ref = $sth->fetch();

    打印转储器 $ref;

    您将看到数据结构布局。有时这是对数组或哈希的不正确索引的问题。

    【讨论】:

      猜你喜欢
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-29
      相关资源
      最近更新 更多