【问题标题】:problems in using DBI使用 DBI 的问题
【发布时间】:2012-03-22 21:14:56
【问题描述】:

我对所有这些东西都不熟悉。我正在尝试执行以下代码

use DBI;

my $dsn = 'DBI:mysql:db:localhost';
my $db_user_name = 'root';
my $db_password = '*******';
my $dbh = DBI->connect($dsn, $db_user_name, $db_password);

my $sth = $dbh->prepare("select id from table where field = 'value'");
$sth->execute();
($id) = $sth->fetchrow_array();
print "id is $id";
$sth->finish();

print 什么也不输出。你能告诉我我做错了什么吗?

提前谢谢你!

【问题讨论】:

  • 绝对没有错误检查,所以我们无法判断您是否无法连接,是否无法查询表(它甚至存在吗?),查询是否成功,或者是否返回零行。试试my $dbh = DBI->connect($dsn, $db_user_name, $db_password) or die "Could not connect!";my $sth = $dbh->prepare("select id from table where field = 'value'") or die $dbh->errstr;$sth->execute or die $dbh->errstr;。另外,请确保use strict;use warnings;
  • @Eugeny89 - 该代码对我有用。 field 列的数据类型是什么?。
  • @JackManey,感谢您非常有用的评论。添加错误检查后,我看到问题是该字段的值包含'@'
  • 更好,my $dbh = DBI->connect($dsn, $db_user_name, $db_password, {RaiseError => 1})。那么你就不需要到处“或死”了。

标签: perl dbi


【解决方案1】:

您在其中一个 cmets 中说您的值中有一个 @。如果您遇到报价问题,您应该使用占位符。让数据库驱动为您处理引用问题:

my $sth = $dbh->prepare("select id from table where field = ?");
$sth->execute($some_value);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    • 2011-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2011-06-07
    相关资源
    最近更新 更多