Perl

There are a few ways to use Perl™ to connect to a SQL Server™ using FreeTDS™.

DBD::ODBC

The recommended choice is DBD::ODBC with the FreeTDSODBC driver.

DBD::Sybase

You may also use DBD::Sybase from Michael Peppler. Despite the name it works for any Sybase or Microsoft SQL Server™. DBD::Sybase uses the CT-Library API and works well. However the project has not been updated for a while.

Sybperl

Finally, you can use Sybperl. Scripts written against Sybperl will not run against other databases the way DBI scripts will. However, it will be familiar ground for those who know DB-Library.

Building and using the Perl modules

Example 7.2. Building DBD::ODBC

	$ cd DBD-ODBC-0.28
	$ export SYBASE=/usr/local/freetds
	$ export ODBCHOME=/usr/local
	$ export DBI_DSN=dbi:ODBC:JDBC
	$ export DBI_USER=guest
	$ export DBI_PASS=sybase
	$ perl Makefile.PL
	$ make
	$ sudo make install


[Note]Note

We used the public JDBC server logins for our configuration here. You'll want to replace these with ones suitable to your environment.

Example 7.3. Connect to a server with DBD::ODBC

	#!/usr/local/bin/perl
	#
	use DBI;
	
	my $dbh = DBI->connect("dbi:ODBC:JDBC", 'guest', 'sybase', {PrintError => 0});
	
	die "Unable for connect to server $DBI::errstr"
		unless $dbh;
	
	my $rc;
	my $sth;
	
	$sth = $dbh->prepare("select \@\@servername");
	if($sth->execute) {
		while(@dat = $sth->fetchrow) {
			print "@dat\n";
		}
	}
	


Example 7.4. Building DBD::Sybase

	$ cd DBD-Sybase-0.91
	$ export SYBASE=/usr/local/freetds
	$ perl Makefile.PL
	$ make
	$ sudo make install


There will be some output about missing libraries after perl Makefile.PL. These are normal.

The following example will attach to Sybase's public JDBC server and run a simple query (it can be found in samples/test.pl):

Example 7.5. Connect to a server with DBD::Sybase

	#!/usr/local/bin/perl
	#
	use DBI;
	
	my $dbh = DBI->connect("dbi:Sybase:server=JDBC", 'guest', 'sybase', {PrintError => 0});
	
	die "Unable for connect to server $DBI::errstr"
		unless $dbh;
	
	my $rc;
	my $sth;
	
	$sth = $dbh->prepare("select \@\@servername");
	if($sth->execute) {
		while(@dat = $sth->fetchrow) {
			print "@dat\n";
		}
	}
	


You'll note this is the same program as for DBD::ODBC with the exception of the connect statement. Welcome to the magic of DBI!