0

I am using perl 5.24. I am trying to learn Perl.

I had written a simple Perl code to connect to a DB. But gives error stating

DBI connect('database=vms','DBA',...) failed: (no error string) at simpleperl.pl line 13.

The code is

#!/usr/bin/perl

use DBI;
use DBD::SQLAnywhere;

my $driver = "SQLAnywhere"; 
my $database = "vms";
my $dsn = "DBI:$driver:database=$database";
my $userid = "DBA";
my $password = "admin";
my $dbh = DBI->connect($dsn, $userid, $password,{RaiseError => 1}) or die ("died connection:$DBI::errstr");

if($dbh)
{
    print "Connection Established";
}

Can anyone point out what might be the problem here?

Prateek
  • 35
  • 1
  • 7
  • First use `use strict;` and `use warnings;` as those will catch a bunch of errors. And don't `use DBD::` directly. `DBI` will handle the driver for you. – dgw Jul 06 '17 at 11:01
  • I think `database=$database` must be `ENG=$database`. See te comment in the source code: `# If dbname starts with something that doesn't look like # a connect string parameter ('label=value;' format) then # 'ENG=' is prefixed. ` – Jens Jul 06 '17 at 11:02
  • Related: https://stackoverflow.com/q/44906829 – PerlDuck Jul 06 '17 at 11:47

1 Answers1

2

Note the following in DBD::SQLAnywhere documentation:

$dbh = DBI->connect( 'dbi:SQLAnywhere:ENG=demo', $userid, $passwd );

#!/usr/bin/perl

use strict;
use warnings;    
use DBI;

my $driver = "SQLAnywhere"; 
my $database = "vms";
my $dsn = "DBI:$driver:ENG=$database";
my $userid = "DBA";
my $password = "admin";
my $dbh = DBI->connect($dsn, $userid, $password, {RaiseError => 1});

print "Connection established\n";

$dbh->disconnect;

Note also the following:

  • Always use strict and warnings.
  • You do not need use DBD::SQLAnywhere;. DBI will pick the driver based on what you specify in the connection string.
  • You specified {RaiseError => 1} in your connection options. That means, there is no need for the or die. DBI will croak if connect fails.
  • You probably want AutoCommit => 0 to go with that RaiseError => 1.
  • There is no need for the if ($dbh) following the connection attempt. You won't get there unless connect succeeded.

Given that fixing the connection string did not solve the problem and I do not have an instance of a SQLAnywhere database to test things, I am going to recommend you add:

DBI->trace( 5 );

before the connect call, and update your question with the trace information. See also TRACING.

Sinan Ünür
  • 116,958
  • 15
  • 196
  • 339
  • I ran the code which you suggested . It still gives the same error **DBI connect('ENG=vms','DBA',...) failed: (no error string) at AnotherSimplePerl.pl line 12.** – Prateek Jul 06 '17 at 11:22
  • I am assuming there is indeed a database called `vms` to which you can connect via other means. Is that assumption correct? – Sinan Ünür Jul 06 '17 at 11:40
  • Yes there is a database called vms. – Prateek Jul 06 '17 at 12:44