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

Hi!! I know this sounds like a dumb question.But i am still new to perl. I am running it on a win32 platform. How do i connect to a database like Access or SQL server?

Replies are listed 'Best First'.
Re: Connecting to database
by Corion (Patriarch) on Jun 11, 2000 at 20:31 UTC

    You want to take a look at the Win32::ODBC module for ODBC access and together maybe the DBI:: modules for more "native" access to the respective databases. A short search for "ODBC" on search.cpan.org resulted also in DBD::ODBC (you will also need DBI for that one)

(jcwren) Re: Connecting to database
by jcwren (Prior) on Jun 11, 2000 at 20:38 UTC
    You most likely want to be using the DBI module. Here's some sample code that would connect to a MySQL database, retrieve the last record entered, and do something with it.
    my $database = DBI->connect ('DBI:mysql:mydatabase:myserver.com', +'username', 'password') || die; my $command = "SELECT Data,PostedAt FROM WEATHER ORDER BY ID DESC +LIMIT 1"; my $cursor = $database->prepare ($command) or die $database->errst +r . "<br>" . $command; $cursor->execute or die $database->errstr . "<br>" . $command; $DBI::rows == 1 or die "db_read_latest_record returned a value oth +er than 1"; my @row = $cursor->fetchrow_array; $cursor->finish; $database->disconnect; return (@row);
    This is very simplistic but demonstrates connecting to a database, retreiving a record and returning. You need to take a look at 'perldoc DBI'. I don't know what the equivalent of 'perldoc' is on NT, though. My installation doesn't have it, and I have a Linux box to fall back on.

    Connecting to an Access database is similiar, except instead of using 'DBI:mysql', use 'DBI:ODBC'. You'll need to setup a machine data source in the Start | Settings | ODBC Data Sources control applet. The fields for the password and user are slightly different, and can be set to an empty string, since the DSN specifies the access parameters to the database.

    Hopefully, that should be enough to get you started.

    --Chris
Re: Connecting to database
by chromatic (Archbishop) on Jun 11, 2000 at 22:34 UTC
    An example Win32::ODBC connection might look like this (from the Perl DBI book):
    use Win32::ODBC; my $db = new Win32::ODBC("DSN=MyDataDSN;UID=user;PWD=password") || die + Win32::ODBC::Error();
    If you're already familiar with the Perl DBI, you can use DBD::ODBC:  my $dbh = DBI->connect("dbi:ODBC:odbc_dsn"); You'll have to set up a Data Source Name with the ODBC32 applet in the Control Panel.

    disclaimer: I'm working from notes here, as my Win32 programming experience is minimal, and I see no reason to change that. :)

Re: Connecting to database
by Anonymous Monk on Jun 11, 2000 at 21:45 UTC
    Thanx everyone. I am new to perl & am loving every moment of understanding it.