views:

141

answers:

4

I'd like a simple perl script / sub to read a sql server table into a hash, does anyone have a good script or snippet (with 'use's) that can do this given a connection string and table name?

Here's a template:

sub sqltable {    
    my ($connStr,$table) = @_;    
    my ($user, $password, $host) = ($connectstr =~ m|^(.*)/(.*)@(.*)$|); # or whatever    
    my $dbh = DBI->connect("dbi:???:$host",$user,$password, { RaiseError => 1 }); # replace ??? with good SQL Server equivalent
    $dbh-> ???; # anything good for this part?  LongTruncOk?  LongReadLen?    
    return $dbh->selectall_arrayref("select * from $table");    
}
+9  A: 

See selectall_hashref in the Perl DBI page.

Kevin Panko
+1 Wow. Would've saved me a lot of time if I'd known about that earlier!
Andomar
That's a good part of it, thanks. Now I just need help on the first part - how to connect to the sql server given a connection string.
Zartog
+5  A: 

Regarding connecting to SQL Server using Perl,

Adam Bellaire
+1  A: 

You are exactly describing Tie::DBI. The tie facility in Perl allows native data structures (such as arrays and hashes) to represent data that comes from other mechanisms, such as databases and files.

That said, there's a lot of reading you can do on the general subject of database access and management in Perl. There are many full-fledged ORMs available, such as Rose::DB::Object, as well as simpler libraries like DBI for connecting to a DB.

Ether
+1  A: 

I think this is the solution you are looking for.

sub get_db {
  my ($server,$database,$tbl,$username,$password) = @_;
  my $dbh = DBI->connect("dbi:ODBC:DRIVER={SQL Server};SERVER=$server;DATABASE=$database",$username,$password); 
  die "Error connecting to database: Error $DBI::err - $DBI::errstr\n" unless defined($dbh);
  my $rows = $dbh->selectall_arrayref("select * from $tbl");
  $dbh->disconnect;
  return $rows;
}
Sheep