Reputation: 103397
I am trying to run simple perl dbi example script to connect to mysql database and do some inserts.
Code:
#! bin/usr/perl -w
use strict;
use warnings;
use DBI();
my $dbh = DBI->connect(
"DBI:mysql:database=SPM;host=IP Address", "username", "password",
{'RaiseError'=>1}
);
my $dbh->do(
'INSERT INTO payment_methods(name, description)VALUES(CASH, DOLLAR)'
);
my $dbh->disconnect();
But when I try to run this using perl filename.pl
I get following
Can't call method "do" on an undefined value at perldbi.pl line 12
That is where I have used do
for first time.
I have tried to google it and also to tried all different kinds of forum but in vain, if you have any idea as to why this is happening and what is way around for this than it would be really great and I would really appreciate your help.
Upvotes: 1
Views: 5610
Reputation: 118118
You have an extra my
:
my $dbh->do(
'INSERT INTO payment_methods(name, description)VALUES(CASH, DOLLAR)'
);
Get rid of that my
.
You either do not really have warnings
enabled in your script or you are ignoring the warnings:
#!/usr/bin/perl
use strict;
use warnings;
my $x = 1;
my $x = 2;
C:\Temp> t "my" variable $x masks earlier declaration in same scope at ...
Upvotes: 10
Reputation: 27173
Your database connection is failing. So $dbh
is undefined.
Update: Both comments are right. Sinan has the correct answer--the OP is using my on every line.
Upvotes: 1
Reputation: 238048
I doubt it's the reason for the error message, but the values in the insert are probably not right:
VALUES(CASH, DOLLAR)
Should probably be:
VALUES(\'CASH\', \'DOLLAR\')
The \
is required because you're using a '
style string. If you use a "
style string instead, you could leave out the \
:
"... VALUES('CASH','DOLLAR')"
Upvotes: 2
Reputation: 118595
As daotoad said, your DBI->connect
call is failing. Check your connection settings, see if you can connect to the database from the command line, etc. In your Perl script, always check the return value of DBI->connect()
to see if the connection was successful.
my $dbh = DBI->connect("DBI:mysql:database=SPM;host=IP Address",...)
or die sprintf( 'connect() failed. Error: %s', DBI->errstr);
my $dbh->do(q{
INSERT INTO payment_methods(name, description)VALUES(CASH, DOLLAR)
});
...
Upvotes: 1