【问题标题】:DBD::SQLite::db prepare failed: no such table PerlDBD::SQLite::db 准备失败:没有这样的表 Perl
【发布时间】:2017-01-09 14:22:08
【问题描述】:

我创建了一个 SQLite 数据库和一个名为“COMPANY”的表。

我的目的是创建一个模块 (Connect.pm),它祝福 DataBase Handler ($dbh) 是到数据库的连接,并与对象创建后,我可以调用 Connect.pm 中可用的 insert 方法。

当我尝试将数据插入数据库时​​,它给了我以下错误:

DBD::SQLite::db prepare failed: no such table: COMPANY at temp.pl 第 6 行。
DBD::SQLite::db 准备失败:没有这样的表:公司位于 temp.pl 第 6 行。

Connect.pm

package Connect;

use strict;
use DBI;

use Data::Dumper;

sub new {
    my $class = shift;
    my $driver = "SQLite";
    my $database = "WEBSITE.db";
    my $dsn = "DBI:$driver:dbname:$database";
    my $userid = "";
    my $password = "";
    my $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1}) or die $DBI::errstr;
    my $self = { dbh => $dbh};

    print STDERR "Opened database successfully\n";
    bless $self, $class;
    return $self;
}
sub insert {
    my $self = shift;
    my ($id, $firstName, $lastName, $email, $comment) = @_;
    my $sth = $self->{ dbh }->prepare("INSERT INTO COMPANY VALUES (?, ?, ?, ?, ?)");
    my $rv = $sth->execute($id, $firstName, $lastName, $email, $comment) or die $DBI::errstr;

    my $value = "Inserted Successfully";
    if($rv < 0){
        $value = $DBI::errstr;
    }
    return $value;
}

1;

temp.pl

use DBI;
use strict;
use Connect;

my $obj = Connect->new();
my $status = $obj->insert("002", "Test", "User", "a\@b.com", "Comment");

$obj->disconenct();

我可以使用这个程序来创建数据库并查询它,这是可行的。

use DBI;
use strict;
my $driver   = "SQLite";
my $database = "WEBSITE.db";
my $dsn      = "DBI:$driver:dbname=$database";
my $userid   = "";
my $password = "";
my $dbh      = DBI->connect( $dsn, $userid, $password, { RaiseError => 1 } ) or die $DBI::errstr;
my $sth      = $dbh->prepare('INSERT INTO COMPANY VALUES (?, ?, ?, ?, ?)');
my $rv = $sth->execute( "003", "Test", "User", "a\@b.com", "Test Comment" ) or die $DBI::errstr;

【问题讨论】:

  • 您确定您创建的数据库正确吗?当你在命令行中使用sqlite3 时,表在吗?您可以使用.tables 命令从该实用程序显示数据库中的所有表。
  • 一些猜测: 1) 由于您没有指定数据库的绝对路径,因此正在您的工作目录中创建一个新路径,而不是连接到现有的路径。 2) 您在数据库和/或表名中打错字(例如,实际名称是 Company,而不是 COMPANY)。 3)您实际上从未成功创建表。
  • 感谢您的回复。
  • 感谢您的回复。数据库创建正确,数据库名或表名没有错误。请注意,当我尝试使用下面的代码(在下一条评论中)插入时,它工作正常,但是当我尝试使用 OO 模型时,即上面的问题摘要部分,它给了我这个错误,
  • 使用 DBI;使用严格;我的 $driver = "SQLite";我的 $database = "WEBSITE.db";我的 $dsn = "DBI:$driver:dbname=$database";我的 $userid = "";我的 $password = "";我的 $dbh = DBI->connect($dsn, $userid, $password, { RaiseError => 1 }) 或死 $DBI::errstr;我的 $sth = $dbh->prepare('INSERT INTO COMPANY VALUES (?, ?, ?, ?, ?)'); my $rv = $sth->execute("003", "Test", "User", "a\@b.com", "Test Comment") or die $DBI::errstr;

标签: database perl dbi


【解决方案1】:

您模块中的 DSN 错误:“DBI:$driver:dbname:$database”应该是“DBI:$driver:dbname=$database”(dbname 后面应该有等号,而不是冒号)。 ThisSuitIsBlackNot 1 月 10 日 15:57 发布是正确答案...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-18
    • 2012-10-16
    相关资源
    最近更新 更多