views:

261

answers:

1

I know there is a similar question: http://stackoverflow.com/questions/896985/connect-to-sql-server-2005-from-perl-and-do-a-select , but I tried the accepted answer and am unable to get it to work.

Assuming I have a db named test, and would love to do a select from mytable (select id, name from mytable)

Code is from the link above with updated dsn:

use strict;
use warnings;
use DBI;

# Insert your DSN's name here.
my $dsn = 'database=test'

# 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;

This is what I got when running the script: Can't connect to data source 'ODBC::database=test' because I can't work out what driver to use (it doesn't seem to contain a 'dbi:driver:' prefix and the DBI_DR IVER env var is not set) at script.pl line 9

Looks like the problem is in the dsn but I have no idea how to fix it (I am on sql 2005, active perl 5.10 and windows xp).

Edit: I used the following code to verified whether ODBC is installed. use DBI;

print join (", ", DBI->installed_versions);

Output: It looks like ODBC is indeed in the list.

ADO, CSV, DBM, ExampleP, File, Gofer, ODBC, SQLite, Sponge, mysql

What am I missing?

A: 

Try setting your DSN to something like:

my $dbh = DBI->connect("dbi:ODBC:test", 'username', 'password')

If that doesn't work, ensure you have DBD::ODBC installed by running:

perl -MDBI -e 'DBI->installed_versions;'
mopoke
I tried your solution and doesn't work, ODBC is in the list when running the code.Since I can't post code here, please see my code in the answer.
steven hong
Can't connect to data source 'ODBC::test' because I can't work out what driver to use (it doesn't seem to contain a 'dbi:driver:' prefix and the DBI_DRIVER envvar is not set) at script.pl line 6
steven hong
Above is what I got after applying your code.
steven hong