Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi Perl monks there, I am getting can't call method 'Sql' on an undefined value. I suspect that there is something wrong with my connection string: I created a user DSN to my local database with windows NT authentication. Here are my codes: (I tried : DSN=SQLServer;UID=sa;PWD=xxx but to no avail)
use strict; use Win32::ODBC; my $data = new Win32::ODBC("DSN=SQLServer") or die "Could not open bec +ause of [$!]"; my $SQL = "SELECT itemNbr, Store_Num FROM sales"; my $connection; if($connection->Sql($SQL))
Would you please advise me? Thank you in advanced

Replies are listed 'Best First'.
Re: can't call method 'Sql' on an undefined value
by terce (Friar) on Jun 28, 2005 at 15:59 UTC
    You have created the variable $connection but not assigned it a value. Should you be using $data instead?
Re: can't call method 'Sql' on an undefined value
by marto (Cardinal) on Jun 28, 2005 at 16:20 UTC
    Hi,

    terce is correct. Also you should close the connection once you are done with it:

    $data->Close();

    You may also want to do some error checking:
    if ($data->Sql($SQL)) { print "The SQL failed.\nError:" .Error(); } else { print "Sql inserted\n" }

    The complete code with the fix pointed out by terce and the above error checking is:

    use strict; use Win32::ODBC; my $data = new Win32::ODBC("DSN=SQLServer") or die "Could not open bec ++ause of [$!]"; my $SQL = "SELECT itemNbr, Store_Num FROM sales"; if ($data->Sql($SQL)) { print "The SQL failed.\nError:" .Error(); } else { print "Sql inserted\n" } $data->Close();

    N.B. The above code is untested but I'm pretty sure that it works.
    If you are unsure of things always read the documentation.
    Hope this helps

    Martin
      You don't need to call Close explicitly. The destructor calls it.