开发者

Perl DBI MySQL Error Msg : Can't call method "do" on an undefined value

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.


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 ...


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')"


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)
});
...


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜