Access SQL Server with Perl DBI

Using the Perl DBI interface, you must first download and install the DBI module (latest version is 1.601). Installing using the cpan command-line tool is the easiest as it will install the dependencies for you.

$ sudo cpan install DBI

Next we are going to build and install FreeTDS. FreeTDS is a set of libraries for Unix and Linux that allows your programs to natively talk to Microsoft SQL Server and Sybase databases. I’m testing this on Mac OS X, so I’m going to install it via MacPorts.

$ sudo port install freetds

Before configuring and installing the DBD::Sybase driver module, make sure that the environment variable SYBASE reflects the path of the FreeTDS installation. MacPorts per default installs FreeTDS in /opt/local.

$ export SYBASE=/opt/local/
$ sudo cpan install DBD::Sybase

To configure FreeTDS to talk to your SQL Server database, edit the configuration file called freedts.conf. In this post, it is located in /opt/local/etc/freetds/freetds.conf.
Finally, here is a simple example to test your installation.

#!/opt/local/bin/perl
use DBI;
my $user = "sa";
my $passwd = "";
my $dbh = DBI->connect( "DBI:Sybase:server=MyServerName",
$user, $passwd, { RaiseError => 1 } )
or die $DBI::errstr;
my $sth = $dbh->prepare("select \@\@servername");
if ( $sth->execute ) {
while ( @dat = $sth->fetchrow ) {
print "servername is @dat\n";
}
}
exit(0);

One thought on “Access SQL Server with Perl DBI”

  1. Thanks. This was very useful.

    For me, I had to use:
    export SYBASE=’/usr/local/Cellar/freetds/0.91′

    And it seemed to work without me having to edit freetds.conf, but other than that, it worked well.

Leave a Reply