DBD::SQLite::db prepare failed: no such table Perl

3.3k views Asked by At

I created a SQLite database and a table named 'COMPANY'.

My intention is to create a module (Connect.pm) which blesses the DataBase Handler ($dbh) which is the connection to the database, and with the object created, I can call the insert method which is available in Connect.pm.

When I try to insert data in to the database, it is giving me the below error:

DBD::SQLite::db prepare failed: no such table: COMPANY at temp.pl line 6.
DBD::SQLite::db prepare failed: no such table: COMPANY at temp.pl line 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();

I can use this program to create the DB and query it, which works.

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;
1

There are 1 answers

0
Ram On

The DSN in your module is wrong: "DBI:$driver:dbname:$database" should be "DBI:$driver:dbname=$database" (there should be an equal sign after dbname, not a colon). Posted by ThisSuitIsBlackNot Jan 10 at 15:57 is the correct answer...