Using the ODBC Framework

The basic steps for using ODBC are similar to the DBI steps we just discussed.

Step 1: Load the necessary Perl module
                     use Win32::ODBC;
Step 2: Connect to the database and receive a connection handle

ODBC requires one preliminary step before making a connection. We need to create a Data Source Name. A DSN is a named reference that stores the configuration information (e.g., server and database name) needed to reach an information source like an SQL server. DSNs come in two flavors, user and system, distinguishing between connections available to a single user on a machine and connections available to any user or service.[26]

DSNs can be created either through the ODBC control panel under Windows NT/2000, or programmatically via Perl. We’ll take the latter route, if just to keep the snickering down among the Unix folks. Here’s some code to create a user DSN to our database on an MS-SQL server:

# creates a user DSN to a Microsoft SQL Server
# note: to create a system DSN, substitute ODBC_ADD_SYS_DSN 
if (Win32::ODBC::ConfigDSN(
                   "SQL Server", 
                    "DESCRIPTION=DSN for PerlSysAdm", 
                    "",  # server name
                    "ADDRESS=",     # server IP addr
                    "DATABASE=sysadm",         # our database
                    "NETWORK=DBMSSOCN",        # TCP/IP Socket Lib
                               print "DSN created\n";
else {
   die "Unable to create DSN:" . Win32::ODBC::Error(  ) . "\n";

Once we have a DSN in place, we can use it to open a connection to our database: ...

Get Perl for System Administration now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.