views:

505

answers:

2

How do I do a SELECT on a SQL Server 2005 from a Perl script?

+1  A: 

Here's a basic example using DBI (edited after comment):

use DBI;

my $dbh = DBI->connect("dbi:Sybase:database=<dbname>;server=<servername>",
    <user>, <password>, 
    { PrintError => 0, RaiseError => 1 });
my $sth = $dbh->prepare( "select field from table" );
my $result = $sth->execute();
while( my $result = $sth->fetchrow_hashref ) {
    print $result->{field};
}
$sth->finish;
$dbh->disconnect;

Hoping to see other answers with a simpler solution :)

Andomar
You don't generally need to specify dbi_connect_method. And I'd recommend using "PrintError =>0, RaiseError => 1" so that SQL errors are thrown... especially since you don't do any error checking ;)You can even shortcut by just saying "for my $row in (@{ $dbh->selectall_arrayref("select field from table", { Slice => {} })}) { print "$row->{field}\n"; }If you're going to use fetchrow_hashref or its friends, worth setting "FetchHashKeyName => 'NAME_lc'" when connecting to the DB too, some people insist on using CamelCase for column names.But apart from all that, fine :)
araqnid
Good suggestions, edited
Andomar
+1  A: 

You will need to use DBI and you are probably best using the DBD::ODBC provider from (CPAN). If you don't know about DBI, then you need to read up about that. There's a book (Programming the Perl DBI) which is old but still valid.

Then something like the following:

use strict;
use warnings;
use DBI;

# Insert your DSN's name here.
my $dsn = 'DSN NAME HERE'

# Change username and password to something more meaningful
my $dbh = DBI->connect("DBI::ODBC::$dsn", 'username', 'password')

# Prepare your sql statement (perldoc DBI for much more info).
my $sth = $dbh->prepare('select id, name from mytable');

# Execute the statement.
if ($sth->execute)
{
    # This will keep returning until you run out of rows.
    while (my $row = $sth->fetchrow_hashref)
    {
        print "ID = $row->{id}, Name = $row->{name}\n";
    }
}

# Done. Close the connection.
$dbh->disconnect;
Nic Gibson
If you're on a Unix-ish platform, DBD::ODBC is likely to be a pain, and it's probably better to use DBD::Sybase with FreeTDS. (Well, UnixODBC was pretty painful last time I tried it)
araqnid
@araqnid - I was going to mention FreeTDS but decided to avoid complicating this. I've had the joy of UnixODBC myself :)
Nic Gibson