Home: Perl Programming Help: DBI:
Use dynamic driver based on ENV var



GISX
New User

Jun 18, 2009, 3:49 PM


Views: 6007
Use dynamic driver based on ENV var

Hello

We have informix and Oracle Databases installed. I have scripts that do the EXACT same functions on both installations. What I've had to when releasing my scripts (code) is edit all pm/pl files 'use' statement to whatever DBD I need. For example:

Say I install my scripts on our UNIX environemnt which has Informix Installed. I need to edit my script 'test.pl' to say 'use DBD::Informix'

Say I also install my scripts on our Windows environment which has Oracle installed. I need to edit my script 'test.pl' to say 'use DBD::Oracle'

I do not have the DBD::Informix installed on the windows environment and also do not have the DBD::Oracle installed on the UNIX environment. They are completly seperate (networks, servers, etc) but I need the same functions on both.

I've searched and connot seem to find it so I am posting it here. Is there a way to say read an ENV variable and use that to decide what DBD to use 'on the fly' (runtime)

EX:


#DBI_DRIVER is specified in ENV settings. Ex: 'Oracle' or 'Informix'
my $db_driver = "DBD::".$ENV{DBI_DRIVER};
use $db_driver;
...
...
...




Please let me know if I am unclear. TIA!!!


FishMonger
Veteran / Moderator

Jun 18, 2009, 4:56 PM


Views: 6002
Re: [GISX] Use dynamic driver based on ENV var

Yes, you can use an environment variable, but the use statement happens at compile time so you need to do the my $db_driver = assignment at compile time as well. However, using this approach, you'd also need to modify the connect statement.

Actually, there is no need to explicitly "use" the DBD module because the DBI module does that for you via a require statement where the needed DBD module is based on the connect statement.

This is how I'd do it.

Code
my $dbd = $ENV{DBI_DRIVER};  # the value is either 'Informix' or 'Oracle' 

my $dbh = DBI->connect("DBI:$dbd:db", 'user', 'password',
{ RaiseError => 1 } )
or die "Error:" . DBI->errstr . "\n";



(This post was edited by FishMonger on Jun 18, 2009, 5:02 PM)


GISX
New User

Jun 18, 2009, 5:30 PM


Views: 5994
Re: [FishMonger] Use dynamic driver based on ENV var

Great info. I will try it out. Thanks!